晚上好! 我使用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
如何在产品实体更新中添加/删除关系?
答案 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);
}