10

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

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

    //Entity code

    return ;
}

或者

function()
{
    using(DBContext context = new DBContext())
    {
        //Entity code
    }
}

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

在 DataAccess Layer 中执行 EF 并将结果存储在 IEnumerable 内部使用

我的DL

function()
{
    IEnumerable something = null;
    using(DBContext context = new DBContext())
    {
        IEnumerable something = ....
    }
    return something;
}

在控制器中

function()
{
    List some = something.ToList();
}

在我的控制器中,我将其作为列表获取,因为我需要执行一些查找操作

"The operation cannot be completed because the DbContext has been disposed Entity Framework"

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

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

4

3 回答 3

8

.ToList()您可以通过在IEnumerable释放上下文之前调用(即在您的using块中)来避免延迟加载 EF 行为

于 2013-04-17T11:26:31.703 回答
6

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

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

请记住,您的上下文可能会返回 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;

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

于 2013-04-17T12:25:56.300 回答
3

Your request will be executed toward the datasource as soon as you'll call .ToList() method.

That's why you cannot perform .ToList() in your Controller as your context as been disposed at the end of the using block.

In your DL method, just do something like:

IEnumerable<Something> function()
{
    using(DBContext context = new DBContext())
    {
      return something.ToList();
    }
}

and in your Controller you'll get an IEnumerable of Something:

var mySomethingIEnumerable = DL.Function();

Hope that helps!

于 2013-04-17T11:50:02.920 回答