You can't simply assign a new child list to an entities object and expect Entities to figure out all your changes. You have to do that yourself. Here's a simple way to do it. It's not the most efficient, and there are tricks to speeding this up, but it works.
First you need to get the existing list of tags. I'm assuming GetBlogByID()
does this. Then, rather than assign a new list of tags, you need to call Remove()
on each tag you want removed. Here's an example:
//Generate a list of tags to remove
var tagsToRemove = _blog.Tags.Except(myNewListOfTags).ToArray();
foreach(var toRemove in tagsToRemove)
_blog.Tags.Remove(toRemove);
...Save changes
Now, as a optimization if there are a lot of tags, I sometimes will do a direct SQL call to delete all the many-to-many relationships, and then add them all again using Entities, rather than have to figure out each add and remove operation.
_myDbContext.Database.ExecuteSqlCommand(
"DELETE FROM BlogTagsManyToManyTable WHERE BlogId = @BlogId",
new SqlParameter("@BlogId", blogId));
I can then add a new list of Blog Tags without having to do any special work.