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
.
Contrary to NHibernate you don’t need to make all your properties virtual but only those where lazy loading should be enabled:
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:
More information: Lazy Loading of Related Data - EF Core | Microsoft Learn