GraphDiff
GraphDiff copied to clipboard
Update and delete children collection at once
trafficstars
Hi
I got this "simple" model
public class Container
{
public int Id { get; set; }
public string Name { get; set; }
public List<Item> Items { get; set; } = new List<Item>();
}
public class Item
{
public int Id { get; set; }
public string Name { get; set; }
public List<Item> LinkedItems { get; set; } = new List<Item>();
}
In order to get the Item n-m Item relation inside an extra table I put the following inside OnModelCreating method
modelBuilder.Entity<Item>()
.HasMany(item => item.LinkedItems)
.WithMany()
.Map(configuration =>
{
configuration
.MapLeftKey("From_ItemId")
.MapRightKey("To_ItemId")
.ToTable("ItemLinks");
});
So let's assume
- That's inside the DB:
Container#1 { Items={ Item#1, Item#2, Item#3 } }Container#2 { Items={ Item#4{ LinkedItems={ Item#1, Item#2 } } }
- I create a new
Container - Move existing
Item#4inside it. - Modify its linked items (1xUpdate
Item#1, 1xDelete referenceItem#2)
var newContainer = new Container {
Name = "new",
Items = {
new Item {Id = 4, Name = "#4", LinkedItems = {new Item {Id = 1, Name = "#1"} }}
}
};
My question is: *Is their a single UpdateGraph() call to
- remove
Item#4fromContainer#2AND - delete not mentioned reference
Item#4->Item#2
I finally got it running but I need 2 calls:
_context.UpdateGraph(newContainer,
map => map.AssociatedCollection(c => c.Items)
);
_context.UpdateGraph(item4,
map => map.AssociatedCollection(i => i.LinkedItems)
);
_context.SaveChanges();
But this solution doesn't help very much since I have to run the second UpdateGraph on each child!