views:

49

answers:

1

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.

A: 
  1. Detach the entity from the old context.
  2. AddObject the entity into the new context.
Craig Stuntz
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.
You need to be more specific.
Craig Stuntz
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.
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
Ok, but how do I handle the relationships? When I detach the object from the context, the relationships are removed as well.
What I would probably do in that case is to select the entity without change tracking in the first place. So set the `query.MergeOption = MergeOption.NoTracking`. Now the entity won't be in the context to begin with.
Craig Stuntz