Using the Entity Framework? Got a many-to-many relationship between two entities?
Recently I’ve been working on a bit of code where there’s a many-to-many relationship between two entities, and I needed to remove the relationship between two entities (“it’s not you, it’s me… honest”).
Thankfully, the entity framework looks after the auto-mapping where the relationship is a standard M:N relationship.One entity appears as a collection on the other, and vice versa.
When inserting records, the process is relatively straightforward. But, as I found, removing the relationship isn’t quite as obvious.
To add the relationship:
{
string connString = ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString;
using(MyEntities ctx = new MyEntities(connString))
{
Item1 item1 = ctx.Item1s.Where(item1 => item1.Item1Id == item1Id).First();
item1.Item2s.Add(ctx.Item2s.Where(item2 => item2.Item2Id == item2Id).First());
ctx.SaveChanges();
}
}
To remove the relationship:
{
string connString = ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString;
using(MyEntities ctx = new MyEntities(connString))
{
Item1 item1 = ctx.Item1s.Include("Item2s").Where(item1 => item1.ItemId == item1Id).First();
Item2 item2 = ctx.Item2s.Where(item2 => item2.Item2Id == item2Id).First();
item1.Item2s.Remove(item2);
ctx.SaveChanges(false);
}
}
Without the Include on the selection of item1 in the removal process, the Entity Framework does not load the related Item2 entities. Hence, when you call Remove, the list is empty, nothing is removed from the list, and the change tracking within the entity context does not recognise that anything’s changed. Therefore, when you call SaveChanges, no updates are done to the database.
Before I figured this out, I was trying a few different things, including loading up the entity on each side of the relationship and calling Remove on both entities to no avail.
If you’ve been trying to deal with a similar problem, with any luck, this will either a) save you time, or b) explain what you’ve been doing wrong and solve your problems.
No comments:
Post a Comment