需要帮助处理具有相同键的对象

发布于 2024-10-20 11:30:35 字数 874 浏览 2 评论 0原文

我收到异常,

An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.

我有一个分离的实体,并且在 ObjectStateManager 中也有键,这是我不明白的。这怎么可能?

我想做的是当实体从客户端(Asp MVC 控制器)返回时将其附加回上下文。

如果我这样做,

db.MyEntity.Attach(myEntity);

我会得到第一个例外。

我知道它是分离的,因为当我尝试调用时,

db.MyEntity.Context.LoadProperty(myEntity, e => e.myProperty);

我得到了我的实体已分离的异常(它应该是分离的,为什么键在 ObjectStateManager 中?)。

总而言之,我认为我的实体在 ObjectStateManager 中有键并且是分离的。我该如何附加它?我错过了什么吗?或者我误解了什么?

感谢您的任何建议。

编辑: 正如 @Ladislav Mrnka 正确指出的那样,我的问题是我在一个请求处理中加载具有相同 id 的实体。我这样做是因为我想要实体的原始值进行比较,如果出现问题我想将其显示回用户,但我需要附加它,这是问题,因为 ObjectStateManager 中仍然存在具有旧值的实体。我附加此实体是因为我还需要显示延迟加载的属性。这样做的正确方法是什么?只是为了对实体进行新查询?

Im geting exception

An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.

I have entity that is detached and also has key in ObjectStateManager, this is what I dont understand. How is this posible?

What Im trying to do is to atach entity back to context when it comes back from client (Asp MVC controller).

If I do this

db.MyEntity.Attach(myEntity);

I get the first exception.

I know that it is detached because when I try to call

db.MyEntity.Context.LoadProperty(myEntity, e => e.myProperty);

I get excetion that my entity is detached (which it should be, why is the key in ObjectStateManager?).

So to sum it up I think I have entity that has key in ObjectStateManager and is detached. How do I attach it? Em I missing something? Or em I misunderstanding something?

Thank you for any suggestions.

Edit:
As @Ladislav Mrnka corectly stated my problem is that Im loading the entity with same id in one request processing. Im doing this because I want original values of the entity for comparing and if there are problems I want to display it back to user, but I need to attach it which is problem because there is entity with old values still present in ObjectStateManager. Im attaching this entity because I also need to display lazy Loaded properties. What is the right aproach to do this? Just to make new query for entity?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

只是偏爱你 2024-10-27 11:30:35

您不能加载实体并附加具有相同 ID 的实体。您必须分离已加载的值或将更改合并到已加载的值中(另请检查 ApplyCurrentValues 方法)。

You can't have loaded entity and attach entity with same Id. You must either detach the loaded one or merge changes into loaded one (also check ApplyCurrentValues method).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文