问题描述
何时应该用实体框架调用DbContext.dispose()?
-
这个虚构的方法是否不好?
public static string GetName(string userId)
{
var context = new DomainDbContext();
var userName = context.UserNameItems.FirstOrDefault(x => x.UserId == userId);
context.Dispose();
return userName;
}
更好吗? p>
Is this better?
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;
}
推荐答案
其实这是两个问题:
- 什么时候我应该使用
Dispose()
- 我的上下文的寿命应该是多少?
答案:
-
从不 。
使用
在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.
参见eg 。简而言之:寿命应该是短,静态上下文不好。
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.
这篇关于实体框架和背景处置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!