Introduction
In the previous lesson, you configured DbContext, migrations, and the SQL Server connection. In this lesson, we will organize that database access inside the Data Access layer instead of spreading EF Core calls across services and controllers. The goal is not simply to create extra classes. The goal is to centralize persistence responsibilities, keep the Business layer independent from most Entity Framework Core details, and provide a consistent way to coordinate several database changes.
We will work with a product catalog. The example will support listing products, finding a product by identifier, searching active products by name, and creating a product through Repository and Unit of Work abstractions. The examples are written for .NET and EF Core. Check the package and namespace names against the version used by your solution.
What Are Repository and Unit of Work?
The Repository pattern
A Repository exposes access to a data source through a collection-like interface. The Application or Business layer does not need to know how SQL is generated or which Entity Framework Core methods are called. A service can call GetByIdAsync or Add, while the details of querying a DbSet remain in the repository implementation.
A repository is not a magical abstraction that removes every database concern. Creating dozens of identical methods for every entity can make the design more complicated rather than better. A practical approach is to use a generic repository for common CRUD operations and specialized repositories for queries that represent a specific business or domain need.
The Unit of Work pattern
A Unit of Work tracks changes made during one business operation and provides a single persistence point. In EF Core, DbContext already supplies much of this behavior through change tracking, relationship management, and SaveChangesAsync. An application may still expose an IUnitOfWork interface to reduce direct DbContext dependencies in the Application layer and to make the shared context used by multiple repositories explicit.
The key principle is not to call SaveChangesAsync after every repository operation. If creating a product and creating its inventory record belong to the same business operation, both changes can be prepared and persisted together. If one step fails, a transaction-based workflow can roll back the complete operation.
Responsibilities Across the Layers
| Layer | Responsibility | What to avoid |
|---|---|---|
| API | Receive HTTP requests, validate input, and create HTTP responses | LINQ queries and direct DbContext access |
| Business | Apply business rules and coordinate DTO and domain flows | Knowing SQL implementation details |
| Data Access | Execute EF Core queries and add, update, or delete entities | Choosing HTTP status codes or UI behavior |
| Domain | Define entities, value objects, and core model rules | Unnecessary SQL Server or EF Core dependencies |
A specialized query usually belongs in the Data Access layer. “Active products with stock greater than zero” is a database-oriented query for this domain. The Business layer can use its result to apply a rule, but it should not carry the details of the Where, Include, and OrderBy chain.
Step 1: Create the Generic Repository Contract
Start by defining the common operations in the Data Access project. Instead of returning IQueryable from GetAllAsync, this example returns a materialized list. This prevents query composition from being scattered across upper layers and keeps database execution under the Data Access layer's control.
public interface IRepository<T> where T : class
{
Task<IReadOnlyList<T>> GetAllAsync(CancellationToken cancellationToken = default);
Task<T?> GetByIdAsync(int id, CancellationToken cancellationToken = default);
Task AddAsync(T entity, CancellationToken cancellationToken = default);
void Update(T entity);
void Delete(T entity);
}In this design, AddAsync adds the entity to the context but does not immediately execute an INSERT command. Update and Delete notify the context about the intended state change. Persisting those changes is the responsibility of the Unit of Work. This separation is important when several changes must be saved as one operation.
Step 2: Implement the Generic Repository
Now implement the contract using AppDbContext. When a query is read-only, AsNoTracking can reduce unnecessary change-tracker overhead. You should still choose tracking behavior deliberately if the returned entity will later be updated.
using Microsoft.EntityFrameworkCore;
public class Repository<T> : IRepository<T> where T : class
{
protected readonly AppDbContext Context;
protected readonly DbSet<T> Entities;
public Repository(AppDbContext context)
{
Context = context;
Entities = context.Set<T>();
}
public async Task<IReadOnlyList<T>> GetAllAsync(
CancellationToken cancellationToken = default)
{
return await Entities
.AsNoTracking()
.ToListAsync(cancellationToken);
}
public async Task<T?> GetByIdAsync(
int id,
CancellationToken cancellationToken = default)
{
return await Entities.FindAsync(new object[] { id }, cancellationToken);
}
public async Task AddAsync(
T entity,
CancellationToken cancellationToken = default)
{
await Entities.AddAsync(entity, cancellationToken);
}
public void Update(T entity) => Entities.Update(entity);
public void Delete(T entity) => Entities.Remove(entity);
}FindAsync can first check entities already tracked by the context and then query the database. This makes it useful for identifier lookups. More complex filters, related data, and projections are often clearer when expressed through specialized repository methods.
Step 3: Put Domain-Specific Queries in a Specialized Repository
Generic CRUD methods are not enough for product listing. Filtering active products by name and ordering them by name represents a product-specific query, so define a specialized contract.
public interface IProductRepository : IRepository<Product>
{
Task<IReadOnlyList<Product>> GetActiveProductsAsync(
string? search,
CancellationToken cancellationToken = default);
Task<Product?> GetDetailsAsync(
int id,
CancellationToken cancellationToken = default);
}Implement the product-specific queries in the concrete repository. The example assumes that the Product entity has Name, Price, StockQuantity, and IsActive properties.
public class ProductRepository : Repository<Product>, IProductRepository
{
public ProductRepository(AppDbContext context) : base(context)
{
}
public async Task<IReadOnlyList<Product>> GetActiveProductsAsync(
string? search,
CancellationToken cancellationToken = default)
{
var query = Entities
.AsNoTracking()
.Where(p => p.IsActive);
if (!string.IsNullOrWhiteSpace(search))
{
query = query.Where(p => p.Name.Contains(search));
}
return await query
.OrderBy(p => p.Name)
.ToListAsync(cancellationToken);
}
public Task<Product?> GetDetailsAsync(
int id,
CancellationToken cancellationToken = default)
{
return Entities
.AsNoTracking()
.FirstOrDefaultAsync(p => p.Id == id, cancellationToken);
}
}When related data is required, add an appropriate Include to the query. Do not automatically include every relationship in every method. Loading large collections can transfer unnecessary data and affect performance. For list screens, projecting only the required fields into a DTO is often a better choice. For large related collections, inspect the generated SQL and evaluate whether a single query or split query is more appropriate.
Step 4: Define and Implement the Unit of Work
The Unit of Work exposes repositories that share the same AppDbContext instance. This example has only a Products repository, but more repositories can be added later.
public interface IUnitOfWork : IAsyncDisposable
{
IProductRepository Products { get; }
Task<int> SaveChangesAsync(
CancellationToken cancellationToken = default);
}public sealed class UnitOfWork : IUnitOfWork
{
private readonly AppDbContext _context;
private readonly IProductRepository _products;
public UnitOfWork(AppDbContext context, IProductRepository products)
{
_context = context;
_products = products;
}
public IProductRepository Products => _products;
public Task<int> SaveChangesAsync(
CancellationToken cancellationToken = default)
{
return _context.SaveChangesAsync(cancellationToken);
}
public ValueTask DisposeAsync() => _context.DisposeAsync();
}In ASP.NET Core, DbContext and its repositories are usually registered with a Scoped lifetime. This allows one context instance to be used during an HTTP request. Registering the context as a singleton can cause thread-safety problems and can mix tracked changes between requests.
Step 5: Register Dependencies
Register the repository and Unit of Work in the Web API project, which acts as the composition root.
builder.Services.AddScoped<IProductRepository, ProductRepository>();
builder.Services.AddScoped<IUnitOfWork, UnitOfWork>();If AppDbContext was registered with AddDbContext, the repository and Unit of Work receive the same scoped context instance. Do not create a new context inside each repository. Doing so defeats the purpose of one shared persistence boundary.
Step 6: Use the Unit of Work from the Business Layer
The Business service can use the Unit of Work without knowing the query implementation details. The following example shows listing and creation flows.
public class ProductService : IProductService
{
private readonly IUnitOfWork _unitOfWork;
public ProductService(IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
}
public async Task<IReadOnlyList<ProductListDto>> GetActiveAsync(
string? search,
CancellationToken cancellationToken)
{
var products = await _unitOfWork.Products
.GetActiveProductsAsync(search, cancellationToken);
return products.Select(p => new ProductListDto
{
Id = p.Id,
Name = p.Name,
Price = p.Price,
StockQuantity = p.StockQuantity
}).ToList();
}
public async Task<int> CreateAsync(
CreateProductDto dto,
CancellationToken cancellationToken)
{
var product = new Product
{
Name = dto.Name.Trim(),
Price = dto.Price,
StockQuantity = dto.StockQuantity,
IsActive = true
};
await _unitOfWork.Products.AddAsync(product, cancellationToken);
await _unitOfWork.SaveChangesAsync(cancellationToken);
return product.Id;
}
}The API controller should focus on HTTP and DTO responsibilities. Writing _context.Products.Where(...) inside a controller may appear quick, but it moves query ownership to the wrong layer and makes testing and future changes harder.
Common Mistakes
- Saving inside every repository method: This can create partial persistence during multi-step operations. Centralize the save decision in the Unit of Work or Business service.
- Adding every possible operation to a generic repository: Avoid overly broad methods such as
FindByNameorGetPagedAndFilteredwhen their behavior is unclear. Add methods that represent real use cases. - Returning
IQueryableto the API layer: This leaks EF Core details upward and makes query execution timing less predictable. - Expecting an untracked entity to update automatically:
AsNoTrackingis useful for read-only queries, but updates require an intentional tracking or attach strategy. - Putting HTTP or business rules in a repository: A repository retrieves data or reports changes to the context. Authorization, pricing policies, and stock rules belong in the Business layer.
- Registering DbContext as a singleton: DbContext is designed for a short-lived unit of work. Scoped registration is the usual fit for web requests.
Practice Exercise
- Use the generic repository with a
Categoryentity and verify that basic CRUD operations work. - Add
GetInStockAsynctoIProductRepositoryto return active products with a stock quantity greater than zero. - Add a
Categoriesproperty to the Unit of Work and complete its dependency injection registration. - In one Business service operation, create a product and its category relationship, then call
SaveChangesAsynconly once. - Inspect the generated SQL in the application logs. Check whether the listing query transfers unnecessary columns or relationships.
After completing the exercise, you should be able to answer: “Why does this query belong in the Data Access layer, and when should a specialized repository be preferred over a generic repository?”
Conclusion
In this lesson, we centralized database operations in the Data Access layer. The generic repository handled common CRUD operations, the specialized repository handled product-specific queries, and the Unit of Work provided a shared context and one persistence point. We also saw that EF Core's DbContext already contains Repository and Unit of Work behavior. Therefore, these abstractions should be used when they make dependencies and responsibilities clearer, not merely because the pattern names are popular.
The next step is to connect this persistence infrastructure with Business-layer rules and services so that the API can expose complete application workflows.
Sources
- https://learn.microsoft.com/en-us/ef/core/dbcontext-configuration/
- https://learn.microsoft.com/en-us/dotnet/architecture/microservices/microservice-ddd-cqrs-patterns/infrastructure-persistence-layer-design
- https://learn.microsoft.com/en-us/ef/core/querying/related-data/eager
- https://learn.microsoft.com/en-us/ef/core/querying/single-split-queries