views:

118

answers:

1

I have an object which is added to an objectContext ..

after some operation i need to pass it to another objectcontext of the same database but i always face this message :


An entity object cannot be referenced by multiple instances of IEntityChangeTracker.


i need to change tracking information be detach it from the old object and attach it to the new objectcontext..

but in the new scope i doesn't own the old objectContext to detach it before

My question : How to change Tracking information of this object to the new ObjectContext?

A: 

You must Detach the entity from the first context while that context is still in scope. Since contexts are units of work, the fact that you need to do this at all and are having context scoping issues suggests you might want to take a broader look at your design.

Craig Stuntz
i know that i need to attach it but i am working in arepository patternfor example iam i work in delete function which take object without knowing if it is tracked outside or noafter checking if it is attached and find that it is not attached it considered to be one of two cases:1- it is new created object which is not racked yet .( there i will attach it before deleting).2- it is an existing object which come from different objectContext( which i can't attach at is already attached to another object context which i don't own )case 2 is my problem do u think there is design problems?
Ahmed
As I said, the OC is a unit of work. If the unit of work spans multiple calls into the repository, then your OC must live across those multiple calls. My suggestion is to use DI to (1) manage the lifetime of the OC and (2) inject it into the Repository when needed. Using multiple contexts concurrently or in a serial manner across a unit of work will always be painful.
Craig Stuntz
but my case need to use multiple contexts concurrently as i need multiple unit of works i used this code but it produce the same error but only changed the entity state to detached :IEntityWithChangeTracker trackedEntity = entity as IEntityWithChangeTracker;trackedEntity.SetChangeTracker(null);_objectSet.Attach(entity)the same error :An entity object cannot be referenced by multiple instances of IEntityChangeTracker.
Ahmed
If you "need" multiple units of work concurrently and interacting, then you've found your design problem.
Craig Stuntz