约定配置 主要规则: 1、表名采用DbContext中对应DbSet的属性名。 2、数据表列的名字采用实体类属性的名字,列的数据类型采用和实体类属性类型最兼容的类型。 3、数据表列的可空性取决于对应实体类属性的可空性。 4、名字为Id 的属性为主键,如果主键为short、int、long类型,则默认采用自增字段,如果主键为Guid类型,则默认采用默认的Guid生成机制生成主键值。
两种配置方式 1、Data Annotation 把配置以特性(Annotation)的形式标注在实体类中。
1 2 3 4 5 6 7 8 9 10 [Table("T_Perosns")] public class Person { public int id { get; set; } [Required()] [MaxLength(100)] public string name { get; set; } public int age { get; set; } public string sex { get; set;} } }
优点:简单 缺点:耦合
2、Fluent API 1 2 3 4 5 public class PersonEntityConfig : IEntityTypeConfiguration<Person> { public void Configure(EntityTypeBuilder<Person> builder) { builder.ToTable("T_Persons"); } }
优点:解耦 缺点:复杂 两种方法大部分功能重叠可以混用,但是不建议,混用优先级:FluentAPI>Data Annotation>约定
Fluent API 1、视图与实体类映射:
1 2 3 4 //配置类写法 builder.ToView("blogsView"); //DbContext类写法 modelBuilder.Entity<Blog>().ToView("blogsView");
2、排除属性映射:
1 2 3 4 //配置类写法: builder.Ignore(e=>e.name2); //DbContext类写法: modelBuilder.Entity<Blog>().Ignore(b=>b.name2);
3、配置列名:
1 2 3 4 //配置类写法: builder.Property(b=>b.BlogId).HasColumnName("blog_id"); //DbContext类写法: modelBuilder.Entity<Blog>().Property(b=>b.BlogId).HasColumnName("blog_id");
4、配置列数据类型:
1 2 3 4 //配置类写法: builder.Property(b=>b.BlogId).HasColumnType("blog_id"); //DbContext类写法: modelBuilder.Entity<Blog>().Property(b=>b.BlogId).HasColumnType("blog_id");
5、配置主键: 默认把名字为Id或者“实体类型+Id”的属性作为主键,可以用HasKey()来配置其他属性作为主键。
1 2 3 4 //配置类写法: builder.HasKey(c=>c.Number); //DbContext类写法: modelBuilder.Entity<Blog>().HasKey(c=>c.Number);
支持复合主键,但是不建议使用。 6、生成列的值:
1 2 3 4 //配置类写法: builder.Property(b=>b.Number).ValueGeneratedOnAdd(); //DbContext类写法: modelBuilder.Entity<Student>().Property(b=>b.Number).ValueGeneratedOnAdd();
7、可以用HasDefaultValue()为属性设定默认值:
1 2 3 4 //配置类写法: builder.Property(b=>b.Age).HasDefaultValue(6); //DbContext类写法: modelBuilder.Entity<Student>().Property(b=>b.Age).HasDefaultValue(6);
8、 索引:
1 2 3 4 //配置类写法: builder.HasIndex(b=>b.Url); //DbContext类写法: modelBuilder.Entity<Blog>().HasIndex(b=>b.Url);
复合索引:
1 2 3 4 //配置类写法: builder.HasIndex(p=>new {p.FirstName,p.LastName}); //DbContext类写法: modelBuilder.Entity<Person>().HasIndex(p=>new {p.FirstName,p.LastName});
唯一索引:IsUnique() 聚集索引:IsClustered() 9、 用EF Core太多高级特性的时候谨慎,尽量不要和业务逻辑混合在一起,以免“不能自拔”。比如Ignore、Shadow、Table Splitting等