-
Notifications
You must be signed in to change notification settings - Fork 226
Lazy Loading
-
In your
<database>.tt
file, setSettings.UseLazyLoading = true;
-
Make sure your connection string has
;MultipleActiveResultSets=True
in it.
-
Install NuGet package:
install-package Microsoft.EntityFrameworkCore.Proxies
-
Include
UseLazyLoadingProxies();
in your database context. For example:// Either in startup.cs public void ConfigureServices(IServiceCollection services) { services.AddDbContext<ApplicationDbContext>(options => options .UseSqlServer(Configuration.GetConnectionString("DefaultConnection")) .UseLazyLoadingProxies()); ... } // Or in the database context protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { if (!optionsBuilder.IsConfigured) { optionsBuilder.UseSqlServer(@"Data Source=(local);Initial Catalog=Demo;Integrated Security=True;MultipleActiveResultSets=True;Encrypt=false;TrustServerCertificate=true"); optionsBuilder.UseLazyLoadingProxies(); } }
If you are creating a website then it's best not to use Lazy Loading as the database context is short-lived (typically less than a second), can add many round-trips to the database, and you tend to know up front what data you need for the view.
Prefer to .Include(p => p.Address)
your related entities to load them up front in a single database call.
If you want to stay with lazy loading, that's completely fine, so long as you are aware of the extra round trips to the database. Further reading here.
Lazy loading and serialization don’t mix well, and if you aren’t careful you can end up querying for your entire database just because lazy loading is enabled. Further reading here