处理多对多的关系C#

时间:2017-06-07 17:17:39

标签: c# asp.net entity-framework

晚上好! 我使用Asp.net MVC和EF。 我有2个型号

 public class Product
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public ICollection<Category> categories { get; set; }
    }

    public class Category
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public ICollection<Product> products { get; set; }
    }
如果我添加新产品,多对多添加正常工作,但如果我尝试更新产品实体,新关系不会添加。 我添加了这样的新产品

Product product= new Product{...};
product.categories.Add(db.Categories.First())//example

如何在产品实体更新中添加/删除关系?

1 个答案:

答案 0 :(得分:0)

首先,您的ICollection<T>应该是虚拟财产:

public class Product
{
    public int ID { get; set; }
    public string Name { get; set; }
    public virtual ICollection<ProductCategory> ProductCategories { get; set; }
}

public class Category
{
    public int ID { get; set; }
    public string Name { get; set; }
    public virtual ICollection<ProductCategory> ProductCategories { get; set; }
}

接下来,在两者之间创建一个关联表:

public class ProductCategory
{
    public virtual Product Product { get; set; }
    public virtual Category Category { get; set; }
}

然后在dbContext中添加关系:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
   modelBuilder.Entity<ProductCategory>()
       .HasKey(c => new { c.CategoryId, c.ProductId });

   modelBuilder.Entity<Product>()
       .HasMany(c => c.ProductCategories)
       .WithRequired()
       .HasForeignKey(c => c.ProductId);

   modelBuilder.Entity<Category>()
       .HasMany(c => c.ProductCategories)
       .WithRequired()
       .HasForeignKey(c => c.CategoryId);  
}