Sparked
Sparked

Reputation: 874

Lazy Loading not working in EntityFramework Core

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.

Upvotes: 3

Views: 4309

Answers (2)

George Wurthmann
George Wurthmann

Reputation: 489

I solved my problem in EF Core 2.1 using UseLazyLoadingProxies:

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        => optionsBuilder
        .UseLazyLoadingProxies();

You now need to manually specify that you want it enabled.

Upvotes: 2

Tseng
Tseng

Reputation: 64298

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.

Upvotes: 3

Related Questions