Entity Framework: updating join tables

I have the following table setup:

  • Order (ID)
  • Product (ID) [where ProductID 1 and 2 already exist]
  • OrderProduct (OrderId, ProductID) [two FK'ng keys for order and product tables]

And I am trying to add a record to the Order table by assigning two products in the following order:

var order = new Order();
order.Products.Add(new Product {ID=1});
order.Products.Add(new Product {ID=2});

db.SaveChanges();

      

The problem is this: When you save the order, the two products are inserted into the DB, rather than referencing the already recorded product records.

Please, help. Thank.

+3


source to share


1 answer


You should use db instead of creating a new product like in this example:

var order = new Order();
order.Products.Add(db.Products.First(p => p.ID = 1));
order.Products.Add(db.Products.First(p => p.ID = 2));

db.SaveChanges();

      



Or you need to "Refresh Link" after creating the product. you can do something like this:

var product = new Product() { ID = 1 };
db.Attach(product);
order.Products.Add(product);

      

+6


source







All Articles