Below are two classes that control database tables using Code First Entity Framework (DbContext).
public class Employee
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string EmployeeName { get; set; }
public int DepartmentId { get; set; }
public Department Department { get; set; }
}
--
public class Department
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string DepartmentName { get; set; }
}
If I retrieve the employees with the line below the navigation property for Department is null:
var employees = _context.Employees.ToList();
However, if I first populate a separate variable with Departments, like this ...
var departments = _context.Departments.ToList();
var employees = _context.Employees.ToList();
... Each employee in the employees list contains the Department object.
My question:
What is best practice to populate the navigation property? I had imagined that Entity Framework would have done this by default and that the ToList() method would handle the lazy loading.
Employees, but not related data likeEmployee.Department. See msdn.microsoft.com/en-us/library/jj574232(v=vs.113).aspx