⚙️ C# / .NET Intermediate

What is the difference between eager, lazy, and explicit loading in EF Core?

Answer

These control how related entities are loaded in EF Core. Eager loading: loads related data as part of the initial query using Include(). var users = context.Users.Include(u => u.Orders).ThenInclude(o => o.Items).ToList(); — one query with JOINs. Best for: known navigations needed by most callers. Lazy loading: related data is automatically loaded when you access a navigation property (on first access). Requires virtual navigation properties and the Microsoft.EntityFrameworkCore.Proxies package. Danger: causes N+1 queries if not careful — each access triggers a separate query. Explicit loading: manually load related data when needed: context.Entry(user).Collection(u => u.Orders).LoadAsync();. Best for: conditionally loading navigations based on business logic. Recommendation: prefer eager loading for known relationships; avoid lazy loading in production (N+1); use explicit loading for conditional scenarios.