EF cannot track two different instance of an entity type with same primary key. You have included the related ThermoformProductCategory
entities, so they are being tracked by the context. When you remove them, they are cleared from the ThermoformProductCategories
property of that product, but they are not removed from the context, and are still being tracked. Finally when you create the new list of ThermoformProductCategory
, some of the new ones' primary key are matching the previous ones' (which already exist in the context)
Since you are creating the entire list again, you don't need to fetch the related entities in the first place. Simply assign a new list and EF will replace the entire list of related entities -
var product = context.ThermoformProducts.FirstOrDefault(i => i.ProductId == entity.ProductId);
if (product != null)
{
// set all the properties
product.ThermoformProductCategories = thermoformCategoryIds.Select(catid => new ThermoformProductCategory()
{
ProductId = product.ProductId,
CategoryId = catid
}).ToList();
context.SaveChanges();
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…