0

I have an object MyProduct which has a property - a List of type List<Category>.

When I insert MyProduct with dbContext.SaveChanges() to the db the product gets inserted into the relevant table in the db and the list of properties get inserted into a linked table in the database which has double primary key eg. ProductId and CategoryId - for each category in the List<Category>.

When I'm trying to update the product and assign the same categories to MyProduct then product gets updated but the context is trying to insert again same category ids values into the linked table.

MyProduct product = _repo.GetProduct(productDto.ProductId);
product.Categories = categories;
_dbContext.SaveChanges();

What I need it to do is rather delete existing pairs ProductId + CategoryId and insert them again according to the values provided in List<Category> in MyProduct or similar, but don't want it to attempt to insert same values again.

How to achieve it?

nickornotto
  • 1,946
  • 4
  • 36
  • 68
  • Try this [answer](https://stackoverflow.com/questions/47043697/to-edit-a-many-to-many-relationship-in-entity-framework-why-must-i-clear-the-co/47070617#47070617). Spoiler: call `product.Categories.Clear();` before assigning. – Slava Utesinov Nov 22 '17 at 06:29
  • This will only clear the property `List` not the database entries – nickornotto Nov 22 '17 at 08:11
  • Did you tried it? – Slava Utesinov Nov 22 '17 at 08:22
  • Yes, and I'm still getting the same: `SqlException: Violation of PRIMARY KEY constraint 'PK_dbo.CategoryProducts'. Cannot insert duplicate key in object 'dbo.CategoryProducts'. The duplicate key value is (9, 125).` Strange thing is that first run debugging it didn't hit the error, second and next time debugging it did. – nickornotto Nov 22 '17 at 08:33
  • And if I try to insert another category it does insert new record in `CategoryProducts` table without deleting the old one. – nickornotto Nov 22 '17 at 08:39

0 Answers0