views:

44

answers:

1

I am using EF4 for the first time and have adopted a strategy of a UnitofWork (DataContext) per View. However, I am having issues and seek advice.

I have a window that displays a list of workstations, when I click the edit button I have another window that displays the selected workstation for edit.

The list view and the edit view use their own UnitOfWork, the selected workstation is passed through to the edit view, however when I try to save the workstation on the edit view I get the following;

An entity object cannot be referenced by multiple instances of IEntityChangeTracker

I know that this is because the workstation object that I passed through to the edit view has a data context associated with it.

How should i deal with this??

+1  A: 

Three choices:

  1. The edit view can re-select the workstation from its own context based on the PK of the entity from the other view.
  2. You can Detach the workstation from the list view and then Attach it to the edit view.
  3. If the list view is read only, you can use MergeOption.NoTracking to prevent the context from tracking changes at all. You still would need to attach it to the edit context.
Craig Stuntz
@Craig, tried detach but it causes the rest of the object graph to be discarded.
David
Detached, not discarded. Not the same thing. At any rate, working with multiple contexts concurrently is non-intuitive for most people. I don't recommend it, when you can avoid it.
Craig Stuntz
@Craig, tried option 3 but when I attach to edit context I get the following exception - An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.
David
That means you're somehow attaching the same instance to the edit context twice. You don't show that code, but that's what's happening.
Craig Stuntz
@Craig, on your detached answer what I am saying is that if I have an object which has an association to another object when I detach the top-level object the associated object becomes null. Is this correct or am I missing something??
David
The associated object shouldn't become null; it should become detached. This may be different if you use Self-Tracking Entities, though.
Craig Stuntz