用using声明实体FrameWork上下文

use*_*567 10 c# entity-framework

这是声明实体框架上下文的最佳实践

function()
{
    DBContext context = new DBContext();

    //Entity code

    return ;
}
Run Code Online (Sandbox Code Playgroud)

要么

function()
{
    using(DBContext context = new DBContext())
    {
        //Entity code
    }
}
Run Code Online (Sandbox Code Playgroud)

我们是否需要在EntityFrameWork中使用?如果是,我的第二个问题

在DataAccess Layer中我执行EF并将结果存储在IEnumerable里面使用

我的DL

function()
{
    IEnumerable something = null;
    using(DBContext context = new DBContext())
    {
        IEnumerable something = ....
    }
    return something;
}
Run Code Online (Sandbox Code Playgroud)

在控制器中

function()
{
    List some = something.ToList();
}
Run Code Online (Sandbox Code Playgroud)

在我的控制器中我得到这个列表,因为我需要做一些查找操作

"The operation cannot be completed because the DbContext has been disposed Entity Framework"
Run Code Online (Sandbox Code Playgroud)

是的我可以从DL返回一个列表,它工作正常

如果我使用IEnumerable,我该如何处理?

pau*_*aul 8

你可以通过调用避免延迟加载EF行为.ToList()IEnumerable情况下被设置前(即你的内using块)


kin*_*ngo 6

是的,使用是最佳实践,因为它可以清理您的上下文.在使用的语句是一个快捷方式:

try {
    // Execute your code inside the using statement
}
finally {
    // Cleanup the context no matter what by calling .Dispose()
}
Run Code Online (Sandbox Code Playgroud)

请记住,您的上下文可能会返回IEnumerables,并且由于EF支持延迟加载,因此在将它们提取到具体集合(即yourResult.ToList())之前,不会填充这些对象.

在这种情况下会出现常见的负面结果:

public IEnumerable<Employee> GetEmployeesInAccounting()
{
    using(var myContext = new MyDbContext())
    {
        return myContext.Employees.Where(emp => emp.Department == 'Accounting');
    }
}

// Code that fails, Assuming Manager is a lazy loaded entity, this results in an exception but it compiles no problem
var acctEmps = GetEmployeesInAccounting();
var something = acctEmps.First().Department.Manager.Department;
Run Code Online (Sandbox Code Playgroud)

您可以使用.Include(emp => emp.Manager)(linq扩展方法)并使用绑定结果来避免这种情况.ToList();