Lazy Loading not working in EntityFramework Core

asp.net-core entity-framework-core

Question

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.

1
2
11/27/2018 12:09:03 AM

Popular Answer

Reading the docs/roadmap you'd have realized that lazy loading is not yet supported in EF Core 1.0/1.1.

Currently only .Include or eager loading is supported, both well documented in the documentation.

You must not assume that all features from EF 6 are available in EF Core. EF Core is a complete rewrite and do not include many of the features of EF6. If you need any of that stuff, you should keep using EF6 instead.

EF Core is good enough for most simple/basic ORM stuff, but even Microsoft recommends to use EF6 for production where you depend on these features.

3
4/2/2017 8:38:55 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow