What are the most important Entity Framework Core best practices for building performant, reliable data access code?
Short answer
Key EF Core best practices include: using AsNoTracking() for read-only queries to skip unnecessary change-tracking overhead; projecting to only the specific columns actually needed rather than loading entire entities; preferring eager loading (Include()) over lazy loading in…
Advertisement
AModel answer
Key EF Core best practices include: using AsNoTracking() for read-only queries to skip unnecessary change-tracking overhead; projecting to only the specific columns actually needed rather than loading entire entities; preferring eager loading (Include()) over lazy loading in performance-sensitive paths to avoid the N+1 query problem, where accessing a related entity per row triggers a separate query for each one instead of a single combined query; wrapping multi-step writes in an explicit transaction to guarantee all-or-nothing consistency; and configuring connection pooling plus transient-fault retry logic (EnableRetryOnFailure()) for resilience against transient cloud database failures.
// Read-only, no change tracking
var users = dbContext.Users.AsNoTracking().ToList();
// Eager loading avoids N+1 queries
var usersWithOrders = dbContext.Users.Include(u => u.Orders).ToList();
// Explicit transaction for multi-step consistency
using var transaction = dbContext.Database.BeginTransaction();
try {
dbContext.Users.Add(new User { Name = "John" });
dbContext.SaveChanges();
transaction.Commit();
} catch { transaction.Rollback(); }Real-world example
A reporting page that was silently issuing hundreds of extra queries (one per row, via lazy-loaded related orders) is fixed by switching to eager loading with Include(), collapsing what had been an N+1 query pattern into a single efficient join, and adding AsNoTracking() since the page never modifies the data it displays.
Likely follow-ups
- How do you detect an N+1 query problem in practice, given it isn't always obvious from the code alone?
- What specific transient failures does EnableRetryOnFailure() protect against in a cloud-hosted database?
Related topics