I assume that you are again adding what you just deleted, since deleting from DbSet also removes the entity from the original child collection from the inside. Then in the second loop you add the object again. You can try to catch this situation like this:
public void UpdateEntityAttributeAssociations(Model model, IEnumerable<Entity> current) { unitOfWork.Context.Entry(model).Collection(m => m.Entities).Load(); ICollection<Entity> original = model.Entities; // perhaps .ToList() necessary // delete List<Entity> toDelete = null; if (original != null) { toDelete = GetToDelete(original, current); foreach (Entity originalEntityToDelete in toDelete) { unitOfWork.Context.Entity.Remove(originalEntityToDelete); } } // add, update if (current != null) { foreach (Entity currentEntity in current) { if (toDelete == null || !toDelete.Contains(currentEntity)) { if (original.Where(originalEntity => originalEntity.IEntity == currentEntity.IEntity).FirstOrDefault() == null) { model.Entity.Add(currentEntity); } } } } }
I also replaced your first line with explicit loading of the child collection, as your procedure for manually requesting child entities seems unfamiliar to me, but I don't think this is a problem (but I don't know).
Edit
I'm not sure my code above helps remove the exception you had. I do not know what will happen if you add an object to a collection that is already in the Deleted state, and if this can cause this exception.
If the code does not help, you can check if you have a problem without a second loop (Insert). And what exactly does GetToDelete look like? And what do your Model and Entity classes and their relationships look like? And is model.Entity really a different collection than model.Entities (or is it a typo)?
Slauma
source share