Entity Framework Core Interview Question #25

What are good DbContext and query practices for an ASP.NET Core application?

EF Core Fundamentals & DbContext Junior Beginner

Quick Interview Answer

Keep DbContext short-lived and normally scoped to one request or unit of work. Do not share one context concurrently between threads, and do not store it in a singleton service.

Detailed Explanation

Keep DbContext short-lived and normally scoped to one request or unit of work. Do not share one context concurrently between threads, and do not store it in a singleton service.

Use asynchronous database APIs for request-time I/O, project only required columns, paginate large collections, and use AsNoTracking for read-only entity queries when tracking is unnecessary.

Keep connection strings and credentials in configuration rather than source code. Review generated SQL for important queries, create appropriate database indexes, avoid excessive round trips, and remember that EF Core performance ultimately depends on sound relational database design.

Code Example

var products = await db.Products
    .AsNoTracking()
    .Where(p => p.IsPublished)
    .OrderByDescending(p => p.Id)
    .Select(p => new ProductListDto
    {
        Id = p.Id,
        Name = p.Name
    })
    .Take(50)
    .ToListAsync(cancellationToken);