1

Good evening! I use Asp.net MVC with EF. I have 2 models

 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; }
    }

many-to many add normaly work, if I add new product, but if i try update product entity,new relationship doesnt add. I add new products like this

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

How I can add/delete relationships in product entity update?

Starter
  • 329
  • 1
  • 3
  • 9
  • Basically the same way. But instead of `new Product` you get the existing from the database - something like `db.Products.FirstOrDefault(p => p.Id == productId)` – Ivan Stoev Jun 07 '17 at 18:50

1 Answers1

0

First, your ICollection<T> should be a virtual property:

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; }
}

Next, create an association table between the two:

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

Then in your dbContext, add the relationships:

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);  
}
C. Helling
  • 1,394
  • 6
  • 20
  • 34