Ian
Ian

Reputation: 4909

EF Where clause in an Include

from this example that I stole from the net:

Company company = context.Companies
                     .Include("Employee.Employee_Car")
                     .Include("Employee.Employee_Country")
                     .FirstOrDefault(c => c.Id == companyID);

if I want a where clause in the include of Employee_Car for example, how do I do that? Say I just want it to retrieve blue cars.

Thanks

Upvotes: 2

Views: 4064

Answers (2)

Mike B
Mike B

Reputation: 1166

Short answer is you can't do it just through using the include. You will need to do a bit of joining. So taking this tip post and the SO answer you could do something like along these lines. (Note not exactly your return type but the closest)

var companyBlueCars = from company in context.Companies
                      where company.Id == companyID 
                      select new 
                      {
                          company,
                          blueCars = from employee in company.Employees
                                     where employee.Employee_Car.Colour == "blue"
                                     select employee.Employee_Car
                      };

(I did make a couple guesses about the data structure but the idea is there.)

Upvotes: 4

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364249

You will not do that because include doesn't support filtering or sorting. You must execute two separate queries to load companies and cars with their filters.

Upvotes: 1

Related Questions