Entity Framework and calling context.dispose()
Solution 1:
In fact this is two questions in one:
- When should I
Dispose()
of a context? - What should be the lifespan of my context?
Answers:
Never 1.
using
is an implicitDispose()
in atry-finally
block. A separateDispose
statement can be missed when an exception occurs earlier. Also, in most common cases, not callingDispose
at all (either implicitly or explicitly) isn't harmful.See e.g. Entity Framework 4 - lifespan/scope of context in a winform application. In short: lifespan should be "short", static context is bad.
1 As some people commented, an exception to this rule is when a context is part of a component that implements IDisposable
itself and shares its life cycle. In that case you'd call context.Dispose()
in the Dispose
method of the component.
Solution 2:
I followed some good tutorials to use EF and they don't dispose the context.
I was a bit curious about that and I noticed that even the well respected Microsoft VIP don't dispose the context. I found that you don't have to dispose the dbContext in normal situation.
If you want more information, you can read this blog post that summarizes why.
Solution 3:
Better still:
public static string GetName(string userId)
{
using (var context = new DomainDbContext()) {
return context.UserNameItems.FirstOrDefault(x => x.UserId == userId);
}
}
No need to return the result from outside the using
scope; just return it immediately and you'll still get the desired disposal behavior.