Boosting Entity Framework Core Performance
Entity Framework Core (EF Core) provides a rich data access experience, but achieving optimal performance requires understanding its inner workings and applying best practices.
1. Use No-Tracking Queries for Read‑Only Data
var products = await context.Products
.AsNoTracking()
.Where(p => p.IsActive)
.ToListAsync();
When you don't need to update entities, AsNoTracking() eliminates change‑tracking overhead.
2. Choose the Right Loading Strategy
Avoid the N+1 query problem by using eager loading wisely.
var orders = await context.Orders
.Include(o => o.Customer)
.Include(o => o.OrderLines)
.ThenInclude(ol => ol.Product)
.ToListAsync();
3. Optimize Bulk Operations
For large inserts, updates, or deletes, consider EFCore.BulkExtensions or raw SQL commands.
await context.BulkInsertAsync(largeList);
await context.BulkUpdateAsync(largeList);
await context.BulkDeleteAsync(largeList);
4. Indexes and Database Tuning
Ensure that columns used in WHERE, JOIN, and ORDER BY clauses are indexed.
| Scenario | Recommended Index |
|---|---|
Filtering by IsActive | CREATE INDEX IX_Products_IsActive ON Products(IsActive) |
Sorting by CreatedDate | CREATE INDEX IX_Orders_CreatedDate ON Orders(CreatedDate) |
5. Caching Frequently Used Data
Cache read‑only lookups using IMemoryCache or a distributed cache like Redis.
var cacheKey = $"Category_{id}";
if (!memoryCache.TryGetValue(cacheKey, out Category category))
{
category = await context.Categories.FindAsync(id);
memoryCache.Set(cacheKey, category, TimeSpan.FromHours(1));
}
6. Measuring Performance
Use ILogger with Microsoft.Extensions.Logging.Console or tools like dotnet-trace to capture query execution times.
var loggerFactory = LoggerFactory.Create(builder =>
{
builder.AddConsole();
builder.AddFilter(DbLoggerCategory.Database.Command.Name, LogLevel.Information);
});
using var context = new AppDbContext(optionsBuilder.Options);
context.GetService().AddProvider(new ConsoleLoggerProvider((_, __) => true, true));
await context.Products.ToListAsync();
Applying these techniques will help you get the most out of EF Core in high‑throughput applications.