Fluent Api is a correspondence between the model and the specified database table
// many the this .HasOptional (. X => X primary table) .WithMany (. X => x polyepitopic) .HasForeignKey (X => X polyepitopic primary table associated id.); // one the this .HasRequired (X => X table 1.) .WithOptional (x => x table 2.);
Table has a primary key, foreign key no
Two entities following table
user table
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;} }
Orders table
public class OrderInfo { public int Id { get; set; } public string OrderNo { get; set; } public string OrderName { get; set; } public virtual User User { get; set; } }
Specifies the correspondence between the user and the order by 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); } }
Adding data will also save the user table and the Order table
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();