Declaring Entity FrameWork Contexts with using

前端 未结 3 2004
广开言路
广开言路 2021-02-08 09:40

Which is the Best Practise in Declaring Entity FrameWork Contexts

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

    //Entity code

    return ;
}


        
相关标签:
3条回答
  • 2021-02-08 10:12

    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!

    0 讨论(0)
  • 2021-02-08 10:31

    Yes, a using is the best practice because it cleans up your context. The Using statement is a shortcut for:

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

    Keep in mind, your context likely returns IEnumerables and since EF supports lazy loading these objects won't be populated until you fetch them to a concrete collection (ie. yourResult.ToList()).

    A common negative outcome occurs in this scenario:

    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;
    

    You can avoid this by using the .Include(emp => emp.Manager) (linq extension method) and binding your result using .ToList();

    0 讨论(0)
  • 2021-02-08 10:34

    You can avoid the lazy-loading EF behaviour by calling .ToList() on the IEnumerable before the context is disposed (i.e. within your using block)

    0 讨论(0)
提交回复
热议问题