I have a ‘EnterpriseEntity’ and ‘TagsEntity’, which have a Many to Many relation in a table
called ‘EnterpriseTag’ this relation table just store the EnterpriseID and TagID.
My concern is about updating this with EF4. I code the following:
//Delete old tags
foreach(var oldTag in e.Tags.ToList())
{
_enterpriseRepository.dbContext.DeleteObject(oldTag);
}
//now insert the new ones, this may have elements from old tag list
foreach(var newTag in newTags)
{
e.Tags.Add(newTag);
}
As you can see the newTags list may have elements from old tag list, but i don’t want to spare time checking that tag by tag.
But when i call .Savechanges() i get the following exception:
Adding a relationship with an entity which is in the Deleted state is
not allowed.
UPDATE:
In my original code i had:
//This delete the Tag object, and i just want to delete the relation
_enterpriseRepository.dbContext.DeleteObject(oldTag);
The correct way to do it:
//this just delete the relation, not the tag
e.Tags.Remove(oldTag);
I would try something like this:
I’m assuming that the old tags which are in the
newTagscollection are the same object instances. If they are the same by entity key you would have to implement anIEqualityComparerforExcept. Just an idea, not sure if it works.