Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting Entity Framework to eager load on Group By

I know that changing the shape of a query causes Entity Framework to ignore the include calls but is there a way I can get it to load the sub properties when I do a select many and a group by. In the following example I want to notify all the employees who have a job booked in a certain time period. Calling .ToArray() after the where only hits the database once but I am doing the SelectMany and GroupBy in memory. Is there a way I can get the SelectMany and the GroupBy to happen on the SQL server and still include the ServiceType and Ship and the Employee details?

I am looking for a way to make one SQL call to the database and end up with a list of Employees who have a job in the time period and the jobs they are assigned to.

var employeeJobs = DataContext.Jobs.
    Include("ServiceType").
    Include("Ship").
    Include("JobEmployees.Employee").
    Where(j => j.Start >= now && j.Start <= finish).
    OrderBy(j => j.Start).
    ToArray().
    SelectMany(j => j.JobEmployees, (j, je) => new { 
        Job = j, 
        Employee = je.Employee 
    }).GroupBy(j => j.Employee);
like image 599
Adrian Brand Avatar asked Sep 18 '12 03:09

Adrian Brand


1 Answers

The following should work:

var q = from e in DataContext.Employees
  where e.Job.Start > ....
  order by e.Job.Start
  select new {Employee = e, Job = e.Job, Ship = e.Job.Ship, ServiceType = e.Job.ServiceType}; // No db hit yet.

var l = q.GroupBy(item=>item.Employee) // no db hit yet.
    .ToList(); // This one causes a db hit.
like image 51
George Polevoy Avatar answered Oct 02 '22 08:10

George Polevoy