Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If I dispose of my ObjectContext, are my entities detached?

In other words, if I retrieve entities, then dispose of my ObjectContext, do I have to explicitly detach all my entities?

like image 502
Fernando Avatar asked Jun 23 '11 15:06

Fernando


3 Answers

Perhaps it depends on the meaning of Detach. Attached entity means that context knows about the entity and it tracks its changes. If you dispose the context it cannot track changes any more and entity is like detached. The like has a real meaning here.

If you are using dynamic proxies (POCO - dynamic change tracking or lazy loading) the proxy itself keeps internally backward reference to the context but it doesn't react on context disposal. It still keeps the reference (btw. this can be source of some nasty memory leaks). This cause a problem in two situations:

  • When you try to attach such entity to another context it will throw some exception that entity can be tracked only by single context (despite the fact that original context is already dead).
  • When you try to access navigation property which wasn't eager loaded you will get ObjectDisposedException because the proxy will trigger lazy loading on disposed context.

The only way to avoid this is either disabling dynamic proxies or manually detaching the entity prior to disposing the context. This has another disadvantage - detaching entity breaks relations.

like image 179
Ladislav Mrnka Avatar answered Nov 15 '22 13:11

Ladislav Mrnka


No you don't have to call detach on your entities. However, if you do something like:

var people = Context.Person.Where(p => p.FirstName == "John");

and then dispose of your context, people will throw an exception, because the IEnumerable has deferred execution. Doing this:

var people = Context.Person.Where(p => p.FirstName == "John").ToList();

will let you still use your people list.

Further,

var john = Context.Person.FirstOrDefault(p => p.Id == 342);

will work after context is disposed, because you've fetched a specific entity and not an enumeration.

like image 27
taylonr Avatar answered Nov 15 '22 12:11

taylonr


Your entities are detached once the context is disposed. See the following post:

Entity Framework Multiple Object Contexts

like image 21
Maciej Avatar answered Nov 15 '22 14:11

Maciej