Entity Framework Core - Lazy Loading

Lazy loading is now available on EF Core 2.1 and here is link to the relevant docs:

https://docs.microsoft.com/en-us/ef/core/querying/related-data#lazy-loading


So it appears that EF Core does not currently support lazy loading. Its coming but may be a while off.

For now if anyone else comes across this problem and is struggling. Below is a demo of using Eager loading which is what for now you have to use.

Say before you had a person object and that object contained a List of Hats in another table.

Rather than writing

var person = _context.Person.Where(p=> p.id == id).ToList();

person.Hats.Where(h=> h.id == hat).ToList();

You need to write

var person = _context.Person.Include(p=> p.Hats).Where(p=> p.id == id).ToList();

And then person.Hats.Where(h=> h.id == hat).ToList(); will work

If you have multiple Lists - Chain the Includes

var person = _context.Person.Include(p=> p.Hats).Include(p=> p.Tickets)
                            .Include(p=> p.Smiles).Where(p=> p.id == id).ToList();

I kinda get why this method is safer, that your not loading huge data sets that could slow things down. But I hope they get Lazy loading back soon!!!

Caz


you can instaling this package for enable lazy loading in EF Core 2.1.

Microsoft.EntityFrameworkCore.Proxies

and then set this config in your ef dbContext

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

"Notice" this package works only on EF Core 2.1 and above.