Fluent Api是指定模型与数据库表之间的对应关系
//一对多 this.HasOptional(x => x.主表).WithMany(x => x.多表).HasForeignKey(x => x.多表关联的主表id); //一对一 this.HasRequired(x => x.表1).WithOptional(x => x.表2);
表中都有对应的主键,没有外键
两个表实体如下
用户表
public class User { public User() { Orders =new HashSet<OrderInfo>() } public int Id{get;set;} public string Name{get;set;} public virtual ICollection<OrderInfo> Orders {get;set;} }
订单表
public class OrderInfo { public int Id { get; set; } public string OrderNo { get; set; } public string OrderName { get; set; } public virtual User User { get; set; } }
通过Fluent Api指定用户与订单的对应关系
public class OrderInfo: EntityTypeConfiguration<OrderInfo> { public OrderInfo() { // Primary Key this.HasKey(t => t.Id); // Table & Column Mappings this.ToTable("OrderInfo"); //添加导航属性
//
this.HasOptional(x => x.User).WithMany(x => x.OrderInfo).HasForeignKey(x => x.Id); } }
添加数据 会同时保存用户表和订单表
User u=new User(); u.Name="张三"; OrderInfo orderInfo=new OrderInfo (); u.Orders.Add(new OrderInfo(){ OrderNo="1234123"}) u.Orders.Add(new OrderInfo(){ OrderNo="12341221213"}) db.User.Add(u); db.SaveChanges();