视频网站为什么有人做,做结构图用什么网站,手机百度网站证书过期,长沙建设教育网官网Fluent API
除了惯例原则与属性数据注解外#xff0c;FluentAPI是另一种支持实体类配置设置的方式。与属性数据注解相比#xff0c;它提供了更广泛的功能与设置弹性。实体类若同时设置了数据注解#xff0c;则采用的优先权是“Fluent API” 数据注解 FluentAPI是另一种支持实体类配置设置的方式。与属性数据注解相比它提供了更广泛的功能与设置弹性。实体类若同时设置了数据注解则采用的优先权是“Fluent API” 数据注解 惯例。一旦设置了Fluent API 无论数据注解还是惯例规则均会被覆盖。
DbContext类定义的OnModelCreating 方法是最常调用FLuent API的地方如下图所示
public class SchoolContext: DbContext
{public KTStoreContext():base(nameKTStore){}public DbSetProduct Products { get; set; }protected override void OnModelCreating(DbModelBuilder modelBuilder){//Write Fluent API configurations here}
} 常用的Fluent API方法配置Fluent API方法作用架构相关配置HasDefaultSchema()数据库的默认架构ComplexType()把一个类配置为复杂类型实体相关配置HasIndex()实体的的索引HasKey()实体的主键可其实现复合主键[Key]在EF core中不能实现复合主键HasMany()1对多的或者 多对多关系 HasOptional()一个可选的关系这样配置会在数据库中生成一个可空的外键HasRequired()一个必有的关系这样配置会在数据库中生成一个不能为空的外键Ignore()实体或者实体的属性不映射到数据库Map()设置一些优先的配置MapToStoredProcedures()实体的CUD操作使用存储过程ToTable()为实体设置表名属性相关配置HasColumnAnnotation()给属性设置注释IsRequired()在调用SaveChanges()方法时属性不能为空IsOptional()可选的在数据库生成可空的列HasParameterName()配置用于该属性的存储过程的参数名HasDatabaseGeneratedOption()配置数据库中对应列的值怎样生成的如计算自增等HasColumnOrder()配置数据库中对应列的排列顺序HasColumnType()配置数据库中对应列的数据类型HasColumnName()配置数据库中对应列的列名IsConcurrencyToken()配置数据库中对应列用于乐观并发检测
举一个简单例子 新建一个FluentApiDemo的控制台应用程序添加Product实体类和上下文类KTStoreModel如下图所示
namespace FluentApiDemo
{public class Product{public int XPId { get; set; }public string Name { get; set; }public int Price { get; set; }public int SPrice { get; set; }public string Category { get; set; }}
} public class KTStoreModel : DbContext{public KTStoreModel(): base(nameKTStoreModel){}protected override void OnModelCreating(DbModelBuilder modelBuilder){modelBuilder.EntityProduct().ToTable(tbProduct);modelBuilder.EntityProduct().HasKey(p p.XPId);modelBuilder.EntityProduct().Property(p p.Name).HasColumnName(ProductName);modelBuilder.EntityProduct().Property(p p.Name).HasMaxLength(50);modelBuilder.EntityProduct().Property(p p.Name).IsRequired();modelBuilder.EntityProduct().Property(p p.Price).HasColumnName(ProductPrice);modelBuilder.EntityProduct().Ignore(p p.SPrice);base.OnModelCreating(modelBuilder);}public virtual DbSetProduct Product { get; set; }}
Main函数中的代码如下图所示 class Program{static void Main(string[] args){using (KTStoreModel db new KTStoreModel()){Console.Write(count:{0},db.Product.Count());Console.ReadKey();}}}
运行后在数据库生成的表结果如下图所示 CodeFirst配置一对一一对多多对多关系 产品类Product和书本类Book是典型的一对一关系产品中可能有书本这个属性也可能没书本这个属性。但是书本必属于产品的一部分。 public class Product{public int Id { get; set; }public string Name { get; set;}public int CategoryId { get; set; }public int Price { get; set; }//导航属性public virtual Book Book { get; set; } } public class Book{public int Id { get; set; }public int Pages { get; set; }public string ISBN { get; set; }public string Author { get; set; }public string Publisher { get; set; }//导航属性public virtual Product Product { get; set; }} 使用Fluent API配置如下 public class kTStoreModel : DbContext{public kTStoreModel(): base(namekTStoreModel){}protected override void OnModelCreating(DbModelBuilder modelBuilder){modelBuilder.EntityProduct().HasOptional(e e.Book)//给Product设置可空的Book属性.WithRequired(e e.Product);//给Book设置不能为空的Product属性,没有Book属性时不能保存}public virtual DbSetProduct Product { get; set; }public virtual DbSetBook Book { get; set; }}
生成的数据表结构如下图所示 书本类Book和作者类Author是典型的多对多关系一本书可能有多个作者一个作者可能写了多本书。 public class Book{public int Id { get; set; }public int Pages { get; set; }public string ISBN { get; set; }public string Publisher { get; set; }//导航属性public virtual ListAuthor Author { get; set; }} public class Author{public int Id { get; set; }public string Name { get; set; }//导航属性public virtual ListBook Book { get; set; }} 使用Fluent API配置如下 public class kTStoreModel : DbContext{public kTStoreModel(): base(namekTStoreModel){}protected override void OnModelCreating(DbModelBuilder modelBuilder){modelBuilder.EntityAuthor().HasMany(e e.Book)//配置一个作者有多本书.WithMany(e e.Author)//配置一本书有多个作者.Map(m m.ToTable(BookAuthor)//生成BookAuthor中间表.MapLeftKey(AuthorId)//因为是通过EntityAuthor开始的所以左表是Author.MapRightKey(BookId));//又表是BookId}public virtual DbSetBook Book { get; set; }public virtual DbSetAuthor Author { get; set; }}
生成的数据库表结构如下图所示 多对多关联——附加数据字段 还有一种多对多关联的情况是存储两个数据表关联信息的数据库表 本身具有其他有效的数据字段。这种情况下实体数据模型必须为此数据表建立起专用的数据类型。 产品Product类和订单Order类是一个多对多的关系OrderDetail存储两个数据表的关联信息并且OrderDetail表中存在其他数据字段。 public class Product{public int Id { get; set; }public string Name { get; set;}public int Price { get; set; }//导航属性public virtual ListOrderDetail OrderDetail { get; set; } } public class Order{public int Id { get; set; }public DateTime OrderDate { get; set; }//导航属性public virtual ListOrderDetail OrderDetail { get; set; }} public class OrderDetail{[Key][Column(Order 0)][DatabaseGenerated(DatabaseGeneratedOption.None)]public int OrderId { get; set; }[Key][Column(Order 1)][DatabaseGenerated(DatabaseGeneratedOption.None)]public int ProductId { get; set; }public int Quantity { get; set; }public int Price { get; set; }//导航属性public virtual Product Product { get; set; }public virtual Order Order { get; set; }} 运行后建立的数据库表结构如下图所示 订单系统中订单主表和明细表是典型的一对多关系。 public class Order{public int Id { get; set; }public DateTime OrderDate { get; set; }//导航属性public virtual ListOrderDetail OrderDetail { get; set; }} public class OrderDetail{public int Id { get; set; }public string ProductName { get; set; }public int Quantity { get; set; }public int Price { get; set; }public int XOrderId { get; set; }//导航属性public virtual Order Order { get; set; }}
使用Fluent API配置如下 public class kTStoreModel : DbContext{public kTStoreModel(): base(namekTStoreModel){}protected override void OnModelCreating(DbModelBuilder modelBuilder){modelBuilder.Conventions.RemovePluralizingTableNameConvention();//取消数据库表复数形式modelBuilder.EntityOrderDetail().HasRequired(od od.Order)//OrderDetail有必须要的导航属性Order.WithMany(o o.OrderDetail)//OrderDetail有集体导航属性OrderDetail.HasForeignKey(x x.XOrderId);//设置外键 }public virtual DbSetOrder Order { get; set; }public virtual DbSetOrderDetail OrderDetail { get; set; }} 也可以使用Fluent API 反向关联代码如下 modelBuilder.EntityOrder().HasMany(o o.OrderDetail).WithRequired(od od.Order).HasForeignKey(od od.XOrderId);
运行后建立的数据库表结构如下图所示 级联删除
级联删除是指父级记录删除时会自动删除子级记录。比如订单主表删除后自动删除订单从表。
在EF中默认是打开级联删除的。
一对多如订单主表删除时订单从表从中外键OrderId变成null。
一对一如删除Product时对应的Book也会删除。
多对多如删除一种book信息时在中间表中对应的作者信息也会删除。
代码如下图所示 modelBuilder.EntityOrderDetail().HasRequired(od od.Order).WithMany(o o.OrderDetail).HasForeignKey(x x.XOrderId).WillCascadeOnDelete();//开启级联删除modelBuilder.EntityOrder().HasMany(o o.OrderDetail).WithRequired(od od.Order).HasForeignKey(od od.XOrderId).WillCascadeOnDelete(false);//关闭级联删除 配置单个实体
我们已经知道了在OnModelCreating()方法中可以通过FluentApi对所有的实体类进行配置然而当实体类很多时我们把所有的配置都放在OnModelCreating()方法中很难维护。EF6允许我们给每一个实体添加一个单独的配置类通过这个配置类来对相应的实体进行配置。
以配置Student实体类为例我们在OnModelCreating()方法中配置Student实体代码如下 public DbSetStudent Students { get; set; }protected override void OnModelCreating(DbModelBuilder modelBuilder){modelBuilder.EntityStudent().ToTable(StudentInfo);modelBuilder.EntityStudent().HasKeyint(s s.StudentKey);modelBuilder.EntityStudent().Property(p p.DateOfBirth).HasColumnName(Birthday).HasColumnOrder(3).HasColumnType(datetime2);modelBuilder.EntityStudent().Property(p p.StudentName).HasMaxLength(50);modelBuilder.EntityStudent().Property(p p.StudentName).IsConcurrencyToken();modelBuilder.EntityStudent().HasManyCourse(s s.Courses).WithMany(c c.Students).Map(cs {cs.MapLeftKey(StudentId);cs.MapRightKey(CourseId);cs.ToTable(StudentCourse);});}
}
我们可以将每个实体类的配置放在一个对应的的配置类如Studnet的实体配置在StudentEntityConfiguratinos配置类中如果程序中有很多实体类采用单独配置的方式可以很好的提高配置的可维护性和可读性。 StudentEntityConfiguratinos类需要继承EntityTypeConfigurationTEntity
public class StudentEntityConfiguration: EntityTypeConfigurationStudent
{public StudentEntityConfiguration(){this.ToTable(StudentInfo);this.HasKeyint(s s.StudentKey);this.Property(p p.DateOfBirth).HasColumnName(DoB).HasColumnOrder(3).HasColumnType(datetime2);this.Property(p p.StudentName).HasMaxLength(50);this.Property(p p.StudentName).IsConcurrencyToken();this.HasManyCourse(s s.Courses).WithMany(c c.Students).Map(cs {cs.MapLeftKey(StudentId);cs.MapRightKey(CourseId);cs.ToTable(StudentCourse);});}
}
在OnModelCreating()方法中使用上边的配置类
public class SchoolDBContext: DbContext
{public SchoolDBContext(): base() {}public DbSetStudent Students { get; set; }protected override void OnModelCreating(DbModelBuilder modelBuilder){// 添加Student实体的配置modelBuilder.Configurations.Add(new StudentEntityConfiguration());}
}