LINQ and associations - When is an Include() required?

时间:2016-02-12 19:46:54

标签: c# entity-framework linq linq-to-entities

This LINQ works as expected and brings back the Department entity associated with a given Employee

Employees.Where(e => e.EmployeeId == 10).Select(e => new {e.Department})

However a similar LINQ expression fails saying Department is null

Employees.Where(e => e.EmployeeId == 10).Department 

The first LINQ statement is able to determine the association between Employees and Department yet the second LINQ expression cannot. If I use the Include("Department") statement in the second LINQ example then it will work and Department will not be null.

Employees.Include("Department").Where(e => e.EmployeeId == 10).Department

Why is Include("Department") not required in the first LINQ statement?

1 个答案:

答案 0 :(得分:2)

The first statement is explicitly asking for Employee.Department object and will only return the department object. What happens is linq builds a sql query that inner joins the department table.

The second statement queries for the employee object. Linq builds a sql query to return the employee object only and since you did not ask for department it does not inner join the department table. After employee object is returned .Department property is being called which is null. The .Department part is called after linq generates the sql query and returns the employee object.

Using include, linq will query for employee table and inner join the department table. This will return both employee and employee.department.

Using select is the best approach because you are returning only exactly what you want. Using include should generally be avoided if possible for performance reasons.