In other words, if I retrieve entities, then dispose of my ObjectContext, do I have to explicitly detach all my entities?
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:
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.
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.
Your entities are detached once the context is disposed. See the following post:
Entity Framework Multiple Object Contexts
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With