Lazy Loading for EF Core
Inspired by and partially based on the blog post: https://weblogs.asp.net/ricardoperes/implementing-missing-features-in-entity-framework-core-part-6-lazy-loading
Enabling LazyLoading in EF Core is extremely easy with this library. You just need to call UseLazyLoading()
(see step 2 below).
However, you will need to slightly modify your entity classes, but just the References, not the Collections (see step 3 below).
Reference the Microsoft.EntityFrameworkCore.LazyLoading
NuGet package (https://www.nuget.org/packages/Microsoft.EntityFrameworkCore.LazyLoading/).
Call UseLazyLoading()
on the DbContextOptionsBuilder
when creating the DbContext
.
public class MyDbContextFactory : IDbContextFactory<MyDbContext>
{
private readonly bool _isLazy;
public MyDbContextFactory (bool isLazy)
{
_isLazy = isLazy;
}
public MyDbContext Create(DbContextFactoryOptions options)
{
var dbContextOptionsBuilder = new DbContextOptionsBuilder<MyDbContext>();
dbContextOptionsBuilder.UseSqlServer("<some_connection_string>");
// Here we enable LazyLoading
dbContextOptionsBuilder.UseLazyLoading();
return new MyDbContext(dbContextOptionsBuilder.Options);
}
}
In your model you need to declare References using the type LazyReference<T>
. Collections don't require additional configuration in your model, just use the ICollection<>
type.
public class Parent
{
public ICollection<Child> Childs { get; set; }
}
public class Child
{
private LazyReference<Parent> _parentLazy = new LazyReference<Parent>();
public Parent Parent
{
get
{
return _parentLazy.GetValue(this);
}
set
{
_parentLazy.SetValue(value);
}
}
}
That's all, LazyLoading enabled! It was so easy, wasn't it?