实体对象不能被IEntityChangeTracker的多个实例引用 [英] An entity object cannot be referenced by multiple instances of IEntityChangeTracker

查看:123
本文介绍了实体对象不能被IEntityChangeTracker的多个实例引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用EF作为ORM。

I use EF as ORM.

我在每个请求上处理 objectContext

我将这些实体保存在缓存层,因为我的服务获得了很多流量。

I save the entities in a cache layer, as my service gets lots of traffic.

我有时得到错误 objectContext已经处理了对于我从缓存获得的某些实体。

I got sometimes get the error objectContext already disposed for some entities that I got from the cache.

我已经将这段代码添加到被从缓存

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:


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

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

使用 Attach()一个不正确的解决方案?

Was using Attach() an incorrect solution from the first place?

推荐答案

正如我们在你的另一个问题(将EF :: attach(实体)将解决objectContext已经被隐藏了吗?),你必须在将实体附加到另一个上下文之前分离实体!

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!

如果 maMDBEntities 是一个新的上下文(不是加载数据的上下文),EntityState不会从此Contexts视点附加。所以你的支票是不够的。

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.Entry(group).State == EntityState.Detached 永远对于没有加载实体的上下文是正确的。

This maMDBEntities.Entry(group).State == EntityState.Detached will always be true for an Context, which did not load the Entity.

这篇关于实体对象不能被IEntityChangeTracker的多个实例引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆