问题描述
什么时候应该使用实体框架调用DbContext.dispose()
?
When should one call DbContext.dispose()
with entity framework?
这种想象的方法不好吗?
public static string GetName(string userId)
{
var context = new DomainDbContext();
var userName = context.UserNameItems.FirstOrDefault(x => x.UserId == userId);
context.Dispose();
return userName;
}
这样更好吗?
public static string GetName(string userId)
{
string userName;
using(var context = new DomainDbContext()) {
userName = context.UserNameItems.FirstOrDefault(x => x.UserId == userId);
context.Dispose();
}
return userName;
}
这样更好吗,也就是说,在使用 using() 时不应该调用 context.Dispose() 吗?
public static string GetName(string userId)
{
string userName;
using(var context = new DomainDbContext()) {
userName = context.UserNameItems.FirstOrDefault(x => x.UserId == userId);
}
return userName;
}
推荐答案
其实这是二合一的问题:
In fact this is two questions in one:
- 我应该什么时候
Dispose()
一个上下文? - 我的上下文的生命周期应该是多久?
答案:
从不 .
using
是try-finally
块中的隐式Dispose()
.如果较早发生异常,则可能会错过单独的Dispose
语句.此外,在大多数常见情况下,根本不调用Dispose
(隐式或显式)无害.
Never .
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.
参见例如实体框架 4 - 生命周期/上下文范围一个 winform 应用程序.简而言之:生命周期应该短",静态上下文不好.
See e.g. Entity Framework 4 - lifespan/scope of context in a winform application. In short: lifespan should be "short", static context is bad.
正如一些人评论的那样,此规则的一个例外是当上下文是实现 IDisposable
本身并共享其生命周期的组件的一部分时.在这种情况下,您将在组件的 Dispose
方法中调用 context.Dispose()
.
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.
这篇关于实体框架和调用 context.dispose()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!