10.2.翻译系列:使用Fluent API进行属性映射【EF 6 Code

原文链接:https://www.entityframeworktutorial.net/code-first/configure-property-mappings-using-fluent-api.aspx

EF 6 Code-First系列文章目录:

Fluent API可以配置实体中的属性,将其映射为数据表中的列。使用Fluent API,你可以改变相应列的名称、数据类型、大小、NULL、Not NUll、主键、外键、以及并发列等等。

我们将使用下面的实体类进行配置:

1public class Student 2{ 3 public int StudentKey { get; set; } 4 public string StudentName { get; set; } 5 public DateTime DateOfBirth { get; set; } 6 public byte[] Photo { get; set; } 7 public decimal Height { get; set; } 8 public float Weight { get; set; } 9 10 public Standard Standard { get; set; } 11} 12 13public class Standard 14{ 15 public int StandardKey { get; set; } 16 public string StandardName { get; set; } 17 18 public ICollection<Student> Students { get; set; } 19}
配置主键以及复合主键

上面的实体代码,并不遵循Code-First约定【对于主键】,因为他们没有名称为Id的属性或者没有{实体名称}+”Id“的属性。所以你可以,使用HasKey()方法配置主键,请记住,modelBuilder.Entity<TEntity>()方法返回的是EntityTypeConfiguration类型的对象。

1public class SchoolContext: DbContext 2{ 3 public SchoolDBContext(): base() 4 { 5 } 6 7 public DbSet<Student> Students { get; set; } 8 public DbSet<Standard> Standards { get; set; } 9 10 protected override void OnModelCreating(DbModelBuilder modelBuilder) 11 { 12 //Configure primary key 13 modelBuilder.Entity<Student>().HasKey<int>(s => s.StudentKey); 14 modelBuilder.Entity<Standard>().HasKey<int>(s => s.StandardKey); 15 16 //Configure composite primary key 17 modelBuilder.Entity<Student>().HasKey<int>(s => new { s.StudentKey, s.StudentName }); 18 } 19}
配置列的名称、类型、顺序

默认的Code-FIrst约定,创建和属性一样的列名,顺序,以及数据类型,你可以重写这个约定:

1public class SchoolContext: DbContext 2{ 3 public SchoolDBContext(): base() 4 { 5 } 6 7 public DbSet<Student> Students { get; set; } 8 public DbSet<Standard> Standards { get; set; } 9 10 protected override void OnModelCreating(DbModelBuilder modelBuilder) 11 { 12 //Configure Column 13 modelBuilder.Entity<Student>() 14 .Property(p => p.DateOfBirth) 15 .HasColumnName("DoB") 16 .HasColumnOrder(3) 17 .HasColumnType("datetime2"); 18 } 19}

正如上面代码所示,Property()方法用来配置实体中的属性,HasColumnName()方法用来配置列名,HasColumnOrder()用来配置顺序,HasColumnType()方法用来配置类型。
enter description here

配置可空、不可空的列

EF 6 API会为原始数据类型的属性,创建Not NULL列,因为原始数据类型不能为空,除非标识了可空的符号?或者Nullable.
使用IsOptional()方法创建可空列,同样使用IsRequired()方法创建不可空列。

1public class SchoolContext: DbContext 2{ 3 public SchoolDBContext(): base() 4 { 5 } 6 7 public DbSet<Student> Students { get; set; } 8 public DbSet<Standard> Standards { get; set; } 9 10 protected override void OnModelCreating(DbModelBuilder modelBuilder) 11 { 12 //Configure Null Column 13 modelBuilder.Entity<Student>() 14 .Property(p => p.Heigth) 15 .IsOptional(); 16 17 //Configure NotNull Column 18 modelBuilder.Entity<Student>() 19 .Property(p => p.Weight) 20 .IsRequired(); 21 } 22}
配置列的大小

Code-First默认会为列创建最大的大小(nvarchar(max)或者varchar(max)),你可以重写这个约定:

1public class SchoolContext: DbContext 2{ 3 public SchoolDBContext(): base() 4 { 5 } 6 7 public DbSet<Student> Students { get; set; } 8 public DbSet<Standard> Standards { get; set; } 9 10 protected override void OnModelCreating(DbModelBuilder modelBuilder) 11 { 12 //Set StudentName column size to 50 13 modelBuilder.Entity<Student>() 14 .Property(p => p.StudentName) 15 .HasMaxLength(50); 16 17 //Set StudentName column size to 50 and change datatype to nchar 18 //IsFixedLength() change datatype from nvarchar to nchar 19 modelBuilder.Entity<Student>() 20 .Property(p => p.StudentName) 21 .HasMaxLength(50).IsFixedLength(); 22 23 //Set size decimal(2,2) 24 modelBuilder.Entity<Student>() 25 .Property(p => p.Height) 26 .HasPrecision(2, 2); 27 } 28}

正如上面代码所示,我们使用HasMaxLength()方法配置列的大小,IsFixedLength()方法会将列的类型从nvarchar转到nchar.HasPrecision()可以配置decimal数据类型的属性的精度。

配置并发列

你可以使用ConcurrencyToken()方法配置并发列,例如:

1public class SchoolContext: DbContext 2{ 3 public SchoolDBContext(): base() 4 { 5 } 6 7 public DbSet<Student> Students { get; set; } 8 public DbSet<Standard> Standards { get; set; } 9 10 protected override void OnModelCreating(DbModelBuilder modelBuilder) 11 { 12 //Set StudentName as concurrency column 13 modelBuilder.Entity<Student>() 14 .Property(p => p.StudentName) 15 .IsConcurrencyToken(); 16 } 17}

上面的代码中,StudentName列是并发列,所以更新和删除的时候,这个列名将会在where子句中。
你同样可以使用IsRowVersion()来配置并发列,只不过这个IsRowVersion()只能用在byte[]数组类型的属性上。

点赞
收藏

评论区

加载中...

相关推荐

MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1

文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s

Oracle 分组与拼接字符串同时使用

SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(

MySQL部分从库上面因为大量的临时表tmp_table造成慢查询

背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_

皕杰报表之UUID

​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为

手写Java HashMap源码

HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22

2020年前端实用代码段,为你的工作保驾护航

有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )