一、建立一对多联系
使用的例子为Product与Category,一个种类(Product)对应多个商品(Product)
1.外键列名默认约定
在“一”这边的实体增加一个集合属性(public virtual ICollection<Product> Products { get; set; }),在“多”这边的实体增加两个属性(1.public int CategoryID { get; set; } 2.public virtual Category Category { get; set; })。其中Product实体的CategoryID要为Product实体的名字+ID(d)具体代码如下:
public class Product { public int Id { get; set; } public string ProductName { get; set; } public decimal UnitPrice { get; set; } public int CategoryID { get; set; } public virtual Category Category { get; set; } }
public class Category { public int Id { get; set; } public string CategoryName { get; set; } public virtual ICollection<Product> Products { get; set; } }
运行后生成的表结构为:
2.使用Data Annotations方式
在“多”的一边的实体的所加的两个属性中的任何一个添加属性注解[ForeignKey("CatId")]
以下演示一种:
public int Id { get; set; } public string ProductName { get; set; } public decimal UnitPrice { get; set; } public int CatId { get; set; } [ForeignKey("CatId")] public virtual Category Category { get; set; }
运行后结果为:
注:ForeignKey("CatId")的CatId要与public int CatId { get; set; }里的CatId一样。
3.Fluent API方式
需要在DbEntity类中添加OnModelCreating方法
public class Category { public int Id { get; set; } public string CategoryName { get; set; } public virtual ICollection<Product> Products { get; set; } }
public class Product { public int Id { get; set; } public string ProductName { get; set; } public decimal UnitPrice { get; set; } public int CatId { get; set; } public virtual Category Category { get; set; } }
protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<Product>() .HasRequired(t => t.Category) .WithMany(t => t.Products) .HasForeignKey(d => d.CatId) .WillCascadeOnDelete(false);//禁用级联删除,默认是开启的 }
运行后结果为:
Entity Framework Code First 模式-建立一对多联系
原文:http://www.cnblogs.com/engineerlm/p/7604325.html