简体   繁体   中英

How To identify DbContext in entity framework?

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

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

I understand it, but my question is :

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.

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM