Yesterday I talked about lazy loading and how you can avoid the usage of proxy objects in NHibernate. Writing that post made me wonder if a similar thing is possible in Entity Framework Core. Let's find out!
Remark: If you want to learn more about the concept of lazy loading check out my previous post first.
Lazy loading in Entity Framework
Lazy loading in Entity Framework works quite similar to NHibernate and also uses a proxy object by default. Therefore you need to install the Microsoft.EntityFrameworkCore.Proxies package and enabling it with a call to UseLazyLoadingProxies
.
.AddDbContext<BookContext>( | |
b => b.UseLazyLoadingProxies() | |
.UseSqlServer(myConnectionString)); |
Contrary to NHibernate you donāt need to make all your properties virtual but only those where lazy loading should be enabled:
public class Book | |
{ | |
public int Id { get; set; } | |
public string Title { get; set; } | |
public int Year { get; set; } | |
public virtual Author Author { get; set; } | |
} |
Lazy loading without a proxy
Lazy loading without a proxy object in Entity Framework IS possible although it requires a bit more work than when using NHibernate.
For Entity Framework you need to explicitly inject the ILazyLoader
service and than use this service to fetch the related data:
public class Book | |
{ | |
private Author _author; | |
public Book() | |
{ | |
} | |
private Book(ILazyLoader lazyLoader) | |
{ | |
LazyLoader = lazyLoader; | |
} | |
private ILazyLoader LazyLoader { get; set; } | |
public int Id { get; set; } | |
public string Title { get; set; } | |
public int Year { get; set; } | |
public Author Author | |
{ | |
get => LazyLoader.Load(this, ref _author); | |
set => _author = value; | |
} | |
} | |
More information: Lazy Loading of Related Data - EF Core | Microsoft Learn