Take the 2-minute tour ×

I've got a scenario in which I want to move a bunch of object graphs between contexts. Specifically, I'm trying to import the contents of one database into another. The there is a context [CurrentContext] connected to the primary DB, and another context [ImportContext] connected to another DB. I'd like to copy the entities from ImportContext into CurrentContext, either inserting new records or updating the existing records. Something like this.

ImportContext.Organization.MergeOption = MergeOption.NoTracking; foreach(var org in ImportContext.Organizations.ToList()) { CurrentContext.Attach(org); // or CurrentContext.AddToOrganization(org); }

When I try the Attach method, the entity isn't saved because the entitystate is Unchanged, and I can't figure out how to mark it as new. Also, it appears Attach doesn't work if the entity is new, because the EntityKey is tied to ImportContext. If I set the EntityKey to null, I lose the associations between the Organization and other entities. AddToOrganization has the same problem with losing the associations, or would fail if the Organization was once already in the CurrentContext.

What's the appropriate approach to doing this type of importing? I'm currently using EF3.5 and can't update the project to EF4.

share|improve this question

1 Answer 1

  1. Detach the entity from the old context.
  2. AddObject the entity into the new context.
share|improve this answer
That doesn't work, in some cases the entity is not new, it's just updated. Also, when I detach the entity, I lose the rest of the object graph, which also needs to be either added or updated. –  user410854 Aug 4 '10 at 19:15
You need to be more specific. –  Craig Stuntz Aug 4 '10 at 20:47
There is a Context [C1] that contains items A,B,C, q,x,y,z and another Context [C2] with C, D, E, x,y,z. A has a collection with items q,x,y; [C1].C has a collection with items x,y,z; [C2].C has a collection with items x,y. I'd like to copy the items in [C1] (A,B,C,q,x,y,z) into [C2]. If the item doesn't exist in [C2], I want it to be added, if it does exist, I want it to be updated. –  user410854 Aug 5 '10 at 0:28
There is no one-step "upsert" feature. You would need to select from [C2], and update if it's there, add if it's not. –  Craig Stuntz Aug 5 '10 at 2:50
Ok, but how do I handle the relationships? When I detach the object from the context, the relationships are removed as well. –  user410854 Aug 5 '10 at 12:24

Your Answer


