使用一个 DBContext 在 Entity Framework 中执行多个 Linq 到实体查询仅连接到数据库一次

Do Multiple Linq To Entity Queries In Entity Framework Using One DBContext Connect Only Once To The Database

我正在尝试使用 Entity Framework 6 从 SQL 服务器数据库中 return 两个结果集。我想通过 运行 2 Linq to Entity 来尝试使用单个 DBContext 的查询。我的问题是通过使用单个 DBContext 是我的请求是否只被数据库连接命中一次。我认为是,但我不确定。

class RequestRefLists
{
  public List<Employee> EmployeeList {get;set;}
  public List<Dept> DeptList {get;set;}
}

    public RequestRefLists GetRequestRefLists()
   {
    RequestRefLists ReqRefLists = new RequestRefLists();

    using(var context= new BusinessDBContext())
    { 
      var queryResult1 = from e in context.Employees
      select e;
      ReqRefLists.EmployeeList = (List<Employee>)queryResult1.ToList();

      var queryResult2 = from d in context.Departments
      select d;
      ReqRefLists.DeptList = (List<Dept>)queryResult2.ToList();
    }
    return ReqRefLists;
   }

您可以使用 Entity Framework Extended Library.

有一个名为 Future queries

的功能
class RequestRefLists
{
    public List<Employee> EmployeeList {get;set;}
    public List<Dept> DeptList {get;set;}
}

public RequestRefLists GetRequestRefLists()
{
    RequestRefLists ReqRefLists = new RequestRefLists();

    using(var context= new BusinessDBContext)
    { 
        var queryResult1 = from e in context.Employees
        select e;
        ReqRefLists.EmployeeList = queryResult1.Future();

        var queryResult2 = from d in context.Departments
        select d;
        ReqRefLists.DeptList = queryResult2.Future();        
    }
    return ReqRefLists;
}

您的查询将在第一次枚举任何集合时延迟执行。

ExecuteFutureQueries builds a batch query from all the stored IFutureQuery objects. Finally, all the IFutureQuery objects are updated with the results from the query.