EF Core DbContext — Complete Guide
In this tutorial, you'll learn about EF Core DbContext. We cover key concepts, practical examples, and best practices.
You create a new DbContext instance manually every time you need the database, forgetting to dispose or misconfiguring the connection. Proper DbContext lifecycle management is critical for performance and correctness in Entity Framework Core.
Wrong
public class ProductService
{
public List<Product> GetProducts()
{
using var ctx = new AppDbContext(); // Manual instantiation
return ctx.Products.ToList();
}
}
Output: Works. But the connection string is hardcoded, no DI, no pooling.
Right
public class ProductService
{
private readonly AppDbContext _ctx;
public ProductService(AppDbContext ctx) // DI injection
{
_ctx = ctx;
}
public List<Product> GetProducts()
{
return _ctx.Products.ToList();
}
}
Registration in Program.cs:
builder.Services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(connectionString));
For high-throughput scenarios, use pooling:
builder.Services.AddDbContextPool<AppDbContext>(options =>
options.UseSqlServer(connectionString));
Prevention
- Register
DbContextwith DI usingAddDbContext. - Inject the context via constructor — never manually instantiate.
- Use
AddDbContextPoolfor web applications to reuse context instances. - Keep context lifetime scoped to the HTTP request or unit of work.
- Override
OnConfiguringonly as a fallback — prefer DI configuration. - Avoid adding too many tracked entities in a single context instance.
- Dispose the context when done — DI containers handle scope disposal.
Common Mistakes with core db context
- Non-exhaustive pattern matches that compile with warnings then crash at runtime
- Misunderstanding that
Stringis[Char]with poor performance for large text operations - Using
foldlinstead offoldl'causing stack overflow on large lists
These mistakes appear frequently in real-world EF code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Learn more about DbContext patterns at DodaTech.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro