Pra*_*ash 5 c# entity-framework
我有以下功能,它接受员工ID并在员工处于活动状态时返回.
public employee GetEmployee(int empId)
{
using(var dbcontext = new dbentities())
{
return dbcontext.employee.Where(emp => emp.id == empId and emp.IsActive == true);
}
}
Run Code Online (Sandbox Code Playgroud)
问题:我使用了一个using
语句,因此每当using块结束时,在using语句中创建的对象将被释放.但是,在实际使用块结束之前,我已经编写了return语句,所以我的对象是否会被处理?我的方法是否正确?处置是如何发生的?
唯一被处理的是using
块中明确陈述的东西 - 即分配给的东西dbcontext
.实际的员工对象没有被处理,并且完全可用 - 但是,由于数据上下文不可用,任何延迟加载或对象导航等功能都将拒绝工作.
顺便说一句 - 它应该是Single
或SingleOrDefault
:
return dbcontext.employee.Single(
emp => emp.id == empId and emp.IsActive == true);
Run Code Online (Sandbox Code Playgroud)
从技术上讲,在IL级别,你不能ret
在try块中(这适用于所有代码,而不仅仅是using
),所以它实际上就像它被编写一样实现:
public employee GetEmployee(int empId)
{
employee <>tmp;
dbentities dbcontext = new dbentities();
try {
<>tmp = dbcontext.employee.Single(
emp => emp.id == empId and emp.IsActive == true);
} finally {
if(dbcontext != null) ((IDisposable)dbcontext).Dispose();
// note that for classes this cast is a no-op and doesn't need any IL;
// the above gets a little more complex for structs - using
// constrained call and no null-check
}
return <>tmp;
}
Run Code Online (Sandbox Code Playgroud)
该using
语句实际上的行为类似于 Try/Finally,如下所示:
try
{
var dbcontext = new dbentities()
return dbcontext.employee.where(emp => emp.id == empId and emp.IsActive == true);
}
finally
{
if(dbcontext != null)
((IDisposable)dbcontext).Dispose(); //Per the comment below
}
Run Code Online (Sandbox Code Playgroud)
无论如何,该finally
块总是会被执行,因此上下文总是会被释放。