1

In thread 1 I have :

MyDbContext contextInstance1 = new MyDbContext();
var entity = contextInstance1.EntityDbSet.First();
// Some work with the entity goes here....

And in thread 2 :

//The entity is passed as an argument from thread 1
contextInstance2.EntityDbSet.Attach(entity);
contextInstance2.EntityDbSet.Remove(entity);

And I get the following error :

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

If I remove the Attach() line, I have an error saying that the entity can't be removed before being firstly attached.

I understand what I have to do, but I don't see how to do it in this situation. My issue is that I have no reference to (and no knowledge of) contextInstance1 in the thread2.

Therefore I am looking for a way to detach the object from the 1st context, before attaching it to the other context. If EF knows that an other instance of the context exists, there should be a way to access it, that's what I'm after.

tobiak777
  • 3,175
  • 1
  • 32
  • 44
  • http://stackoverflow.com/questions/18925111/turn-off-ef-change-tracking-for-any-instance-of-the-context this will help – Ajay Kumar Apr 22 '15 at 10:10
  • I hope the threads don't run parallel? – Gert Arnold Apr 22 '15 at 12:46
  • Why ? =/ They probably do. – tobiak777 Apr 22 '15 at 13:55
  • I've been able to solve my problem using this question : http://stackoverflow.com/questions/25230024/get-dbcontext-from-entity-in-entity-framework The approach is slightly different : here we get the contextInstance1 from the entity instead of creating another. Thank to that I can remove the entity directly from its context. I'm not sure if it'd be necessary to do a "lock" on the context tough following @GertArnold comment – tobiak777 Apr 22 '15 at 13:58
  • I asked because it will be hard to have two context pulling on one and the same object, not knowing when either one can detach it. Esp. if both threads need to update the entity this looks troublesome. – Gert Arnold Apr 22 '15 at 14:41

1 Answers1

0

You could try to detach the entity in contextInstance1 before passing the entity to contextInstance2, like this:

MyDbContext contextInstance1 = new MyDbContext();
var entity = contextInstance1.EntityDbSet.First();
// Some work with the entity goes here....
contextInstance1.Entry(entity).State = EntityState.Detached;
valentin
  • 667
  • 2
  • 12
  • 19
  • I can't do that, DDD, the domain model is persistence-ignorant ; ) The callers are in the domain model. – tobiak777 Apr 22 '15 at 14:01