Declaring Entity FrameWork Contexts with using

前端 未结 3 2120
广开言路
广开言路 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: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 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();

提交回复
热议问题