如何在实体框架中识别DbContext? [英] How To identify DbContext in entity framework?

查看:93
本文介绍了如何在实体框架中识别DbContext?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个项目中有多个对象,并且有一个UNKNOWN的原因EF是一个例外:

I have multyple objects in one Project and for an UNKNOWN reason EF is thrwing an Exception:

无法定义两个对象之间的关系,因为它们是相关的不同的ObjectContext

"Can't define a relation between two objects, because they are asociated to diferent ObjectContext"

我明白了,但我的问题是:

I understand it, but my question is :

对象的上下文?有Id吗?或者是其他东西 ?

How can i do to identify the context of an object? there is an Id ? or something else ?

推荐答案

这是微妙的。很可能你有两个不同的数据库上下文实例,并且已经使用上下文的第一个实例检索了关系中的一个实体,而另一个实体已经被上下文的另一个实例检索。

That is subtle. Most probably you have two different instances of your db context and one of entities in the relation has been retrieved with the first instance of the context while the other entity has been retrieved with the other instace of the context.

这可能很容易发生。例如,在Web应用程序中,您可以拥有请求生命周期的上下文,但您将会将实体存储在会话容器中。然后,当处理另一个请求时,您将从会话中获取实体,并尝试使用它从当前上下文创建与另一个实体的关系。另一个例子 - 您有一个Windows应用程序,并且您在每个表单中实例化了db上下文。然后,您可以从两个不同的上下文中获取内容。

This could easily happen. For example, in a web application you could have a context with the request life time but you store an entity in the session container. Then, when another requrest is processed, you get the entity from the session and try to use it to create a relation to another entity from a current context. Another example - you have a Windows application and you have db context instantiated at each form. Then you get entites from two different contexts.

最简单的解决方法是让ID在不同上下文之间传递。而不是将一个实体放在会话中,将ID放在那里。而不是在表单之间传递实体,传递ID等等。

The simplest workaround for this is to have the IDs passed between different context. Instead of putting an entity into Session, put ID there. Instead of passing entities between forms, pass ID and so on.

这样,当你创建一个关系时,你有一个实体来自一个上下文,而 id 的实体。您使用该ID从当前上下文中检索实体,然后创建一个关系。

This way, when you are to create a relation, you have an entity from one context and the id of the entity from another context. You use the id to retrieve the entity from the current context and then you create a relation.

另一种解决方法是在上下文之间分离和重新连接实体。这通常是不必要的凌乱。

Another way of solving this would be to detach and reattach entities between contexts. This is usually unnecessary messy.

这篇关于如何在实体框架中识别DbContext?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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