Introduction


Entity Framework Core is the go-to ORM for .NET developers, but it's easy to fall into performance traps.


Use AsNoTracking for Read-Only Queries



var posts = await db.Posts
    .AsNoTracking()
    .Where(p => p.IsPublished)
    .ToListAsync();

Avoid N+1 Queries


Always use Include or Select projections to load related data:



var posts = await db.Posts
    .Include(p => p.Author)
    .Include(p => p.Tags)
    .ToListAsync();

Use Compiled Queries


For hot paths, compiled queries eliminate repeated expression tree compilation:



private static readonly Func<AppDbContext, int, Task<Post?>> GetPostById =
    EF.CompileAsyncQuery((AppDbContext db, int id) =>
        db.Posts.FirstOrDefault(p => p.Id == id));

Conclusion


Following these patterns will keep your data access layer fast and maintainable as your application scales.