从所有打开的上下文中分离实体

时间:2015-04-22 10:05:11

标签: c# entity-framework entity-framework-6 dbcontext

在主题1中我有:

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

在主题2中:

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

我收到以下错误:

  

实体对象不能被多个实例引用   IEntityChangeTracker。

如果我删除了Attach()行,我会在首次连接之前发现错误,说明该实体无法删除。

我明白我必须做什么,但在这种情况下我不知道该怎么做。我的问题是我没有在thread2中引用(并且不知道)contextInstance1。

因此,在将对象附加到其他上下文之前,我正在寻找一种从第一个上下文中分离对象的方法。如果EF知道上下文的另一个实例存在,那么应该有一种方法来访问它,这就是我所追求的。

1 个答案:

答案 0 :(得分:0)

在将实体传递给 contextInstance2 之前,您可以尝试在 contextInstance1 中分离实体,如下所示:

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