EF 4.1 How to merge a graph returned by web service into an existing context
I have a scenario where I need to merge in a large graph (over 2000 entities) returned by web service into existing DbContex开发者_运维问答t. So, my first try:
' get new object from web service
Dim newCust = DAL.GetCustomer(ActiveCustomerView.CustomerID)
' attach the object graph into existing context
context.Customers.Attach(newCust)
This create duplicate conflicts in case I try to attach objects containing entities that already exists in the context.
To avoid this problem I’m clearing the local data and then call AcceptAllChanges before attach:
context.Orders.Local.Clear()
context.OrderItems.Local.Clear()
context.Messages.Local.Clear()
context.Contacts.Local.Clear()
context.Parcels.Local.Clear()
context.CustomerTransactions.Local.Clear()
context.ReturnedParcels.Local.Clear()
context.ReturnedOrderItems.Local.Clear()
context.InventoryItems.Local.Clear()
context.Shippments.Local.Clear()
context.Prints.Local.Clear()
DirectCast(context, IObjectContextAdapter).ObjectContext().AcceptAllChanges()
This works but the performance is not acceptable as it takes over 40 sec to clear the data.
Is there any other way to effectively accomplish that? Can I dispose somehow DbSet's instate of clearing them?
I can’t destroy and create new context each time I need to attach the graph because it contains other objects that would get lost.
精彩评论