views:

280

answers:

0

I have many-to-many relationship in LINQ to SQL scheme: Products table, Categories table and ProductCategories table (ProductId, CategoryId fields).

Product prod;
EntitySet<Category> cats = prod.ProductCategories;

Now I have a list of category ids (catIds) and I want to set (overwrite) them as categories of a single product in one operation.

Tried:

prod.ProductCategories.Assign(catIds.Select(x => new ProductCategory{ CategoryId = x })));
db.SubmitChanges();

It works ok, if old category list don't intersect with the new one. But when there are common categories, duplicate key insertion exception is thrown in SubmitChanges function.

How to update the category list in a right way?