C# 一个实体对象不能被多个 IEntityChangeTracker 实例引用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14725831/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
An entity object cannot be referenced by multiple instances of IEntityChangeTracker
提问by Elad Benda
I use EF as ORM.
我使用 EF 作为 ORM。
I dispose the objectContext
on every request.
我处理objectContext
每个请求。
I save the entities in a cache layer, as my service gets lots of traffic.
我将实体保存在缓存层中,因为我的服务获得了大量流量。
I got sometimes get the error objectContext already disposed
for some entities that I got from the cache.
objectContext already disposed
对于从缓存中获得的某些实体,我有时会收到错误消息。
I have added this code to elements that were retrived from the cache
我已将此代码添加到从缓存中检索的元素中
if (maMDBEntities.Entry(group).State == EntityState.Detached)
{
maMDBEntities.Groups.Attach(group);
}
but now I sometimes get this error:
但现在我有时会收到此错误:
An entity object cannot be referenced by multiple instances of IEntityChangeTracker.
一个实体对象不能被 IEntityChangeTracker 的多个实例引用。
Was using Attach()
an incorrect solution from the first place?
Attach()
从一开始就使用了错误的解决方案?
采纳答案by TGlatzer
As we told you in your other question (will EF::attach(entity) will solve objectContext is already desposed?), you have to detach the Entities before attaching it to another Context!
正如我们在您的另一个问题中告诉您的(EF::attach(entity) 会解决 objectContext 是否已经被废弃?),您必须先分离实体,然后再将其附加到另一个上下文!
If maMDBEntities
is a new Context (not the one, which loaded the data), the EntityState is not "attached" from this Contexts point-of-view. So your check is not sufficient.
如果maMDBEntities
是一个新的 Context(不是加载数据的那个),那么从这个 Contexts 的角度来看,EntityState 不是“附加”的。所以你的支票是不够的。
This maMDBEntities.Entry(group).State == EntityState.Detached
will alwaysbe true for an Context, which did not load the Entity.
对于未加载实体的上下文,这maMDBEntities.Entry(group).State == EntityState.Detached
将始终是正确的。