I'm having a bit of trouble getting my head around when entities are attached and change tracked and when they are not. Sorry if this has already been asked. Say I have some code like this:
当附加实体并更改跟踪以及不实时跟踪时,我遇到了一些麻烦。对不起,如果已经问过这个问题。说我有这样的代码:
public MyEntity GetEntity()
{
using (var ctx = new MyObjectContext)
{
return ctx.MyEntitySet.First();
}
}
Then I call it
然后我打电话给它
var result = GetEntity();
Should result be attached or detached from the context?
结果应该与上下文相关联还是脱离?
I was under the impression that when the ObjectContext got disposed the entity lost its change tracking. Or is the Context never getting disposed.
我的印象是,当ObjectContext被处置时,实体失去了它的变化跟踪。或者上下文永远不会被处理掉。
2 个解决方案
#1
If you write that code while the ctx
has been disposed, because you didn't detach the entity from the ctx
you can't attach it to another context. Essentially there remains a backpointer from the Entity to the ctx
, which stops that from happening.
如果在处理ctx时编写该代码,因为您没有从ctx中分离实体,则无法将其附加到其他上下文。从本质上讲,仍然有一个从实体到ctx的backpointer,它阻止了这种情况的发生。
I suppose you could say it is 'psuedo-attached'.
我想你可以说它是'假装的'。
Hope this helps
希望这可以帮助
Program Manager Entity Framework Team
项目经理实体框架小组
#2
The attachment of the object isn't directly related to the context in my understanding. I believe that if the entity keys are set then it is still attached. You can detach the object, but you have to do it manually using the Detach method.
对象的附件与我理解的上下文没有直接关系。我相信如果设置了实体键,那么它仍然是附加的。您可以分离对象,但必须使用Detach方法手动执行此操作。
If you're after a detached object, try detaching it manually. Otherwise what you have done should allow you to update the object and save the changes without re-attaching the object.
如果您正在处理分离的对象,请尝试手动分离它。否则,您所做的事情应该允许您更新对象并保存更改,而无需重新附加对象。
Cheers
#1
If you write that code while the ctx
has been disposed, because you didn't detach the entity from the ctx
you can't attach it to another context. Essentially there remains a backpointer from the Entity to the ctx
, which stops that from happening.
如果在处理ctx时编写该代码,因为您没有从ctx中分离实体,则无法将其附加到其他上下文。从本质上讲,仍然有一个从实体到ctx的backpointer,它阻止了这种情况的发生。
I suppose you could say it is 'psuedo-attached'.
我想你可以说它是'假装的'。
Hope this helps
希望这可以帮助
Program Manager Entity Framework Team
项目经理实体框架小组
#2
The attachment of the object isn't directly related to the context in my understanding. I believe that if the entity keys are set then it is still attached. You can detach the object, but you have to do it manually using the Detach method.
对象的附件与我理解的上下文没有直接关系。我相信如果设置了实体键,那么它仍然是附加的。您可以分离对象,但必须使用Detach方法手动执行此操作。
If you're after a detached object, try detaching it manually. Otherwise what you have done should allow you to update the object and save the changes without re-attaching the object.
如果您正在处理分离的对象,请尝试手动分离它。否则,您所做的事情应该允许您更新对象并保存更改,而无需重新附加对象。
Cheers