Repository and Unit of Work patterns with Entity Framework - help or overhead?
Repository and Unit of Work patterns examined with Entity Framework 6, including generic repositories, focused interfaces, persistence leakage, and transaction boundaries.
Repository and Unit of Work patterns with Entity Framework - help or overhead?
Data access code is appearing in almost every business application, and Entity Framework 6 gives us a productive way to query and save relational data. Teams are often adding Repository and Unit of Work patterns to make this access easier to test and abstract. Sometimes the patterns are creating a useful boundary, and sometimes they are only wrapping DbSet and adding another layer.
In this article, we are going to see what Repository and Unit of Work mean, how they work with Entity Framework, and when they help or become overhead.
TL;DR Summary
- A repository represents a collection-like access boundary for an aggregate or business concept.
- A Unit of Work groups changes and commits them as one application operation.
DbContextalready provides many Unit of Work and repository-like capabilities.- A generic repository can hide useful query behaviour and create leaky abstractions.
- Use explicit repositories when they express business intent or isolate a changing dependency.
- Do not abstract a pattern only to satisfy a diagram.
Challenges
Data access in controllers
When controllers construct DbContext, query entities and call SaveChanges, HTTP concerns and persistence concerns are mixed. Tests need a database and business rules are difficult to locate. This slows feedback and encourages copy-paste queries.
Abstraction without value
A repository with methods named Get, Add and Delete may only forward to DbSet. It gives the illusion of isolation while still leaking IQueryable and Entity Framework exceptions. The team pays maintenance cost without receiving a useful boundary.
Transaction boundaries
Saving each change immediately can leave a business operation half-complete. A news article publication may update status, add an audit record and enqueue an indexing message. We need to define which changes belong to one Unit of Work and what happens when the external message cannot be sent.
What is Repository?
A Repository is an abstraction which represents access to a collection of domain objects or an aggregate boundary.
In simple terms, it provides business-shaped operations such as FindArticle or GetOpenFund, rather than making every caller know table names and joins. A repository does not mean every query in the application must use one generic interface.
What is Unit of Work?
A Unit of Work tracks changes made during one business operation and coordinates committing them.
Simply put, it is the boundary around “all these changes must be saved together”. Entity Framework’s DbContext already tracks entities and SaveChanges commits the tracked changes, so it can act as the Unit of Work implementation.
Why these patterns are important?
The value is in making the application operation visible. When a fund subscription changes a holding and creates an audit record, the code should show that both belong to the same decision. The pattern is useful when it reduces coupling or clarifies a transaction, not when it adds an empty wrapper.
The following diagram depicts an application service using a repository and Unit of Work,

A practical implementation
Define a focused repository
Use a focused interface when the domain has a meaningful boundary,
public interface IArticleRepository
{
Article Find(int articleId);
void Add(Article article);
}
The interface does not expose DbSet or a database connection. This keeps the application from constructing arbitrary persistence queries in every caller.
Implement with Entity Framework 6
public sealed class ArticleRepository : IArticleRepository
{
private readonly NewsDbContext context;
public ArticleRepository(NewsDbContext context)
{
this.context = context;
}
public Article Find(int articleId)
{
return context.Articles.SingleOrDefault(x => x.Id == articleId);
}
public void Add(Article article)
{
context.Articles.Add(article);
}
}
Define an application operation
public void PublishArticle(int articleId, string editor)
{
Article article = articles.Find(articleId);
article.Publish(editor);
context.AuditEntries.Add(AuditEntry.For(articleId, editor));
context.SaveChanges();
}
This operation uses DbContext as the Unit of Work. If the application needs an abstraction, define one around the required operation rather than pretending every persistence feature is identical.
When is it overhead?
Generic repository
A generic repository can be useful for a very simple shared convention, but it often exposes IQueryable<T> and forces all queries through an abstraction which does not understand their intent. A report query and an aggregate update have different needs. Do not hide those differences only to avoid writing a second interface.
Mocking everything
Replacing Entity Framework with mocks does not prove that the query works against the database. Use fast unit tests for domain decisions and focused integration tests for mappings and queries. The test double is like a stunt double: useful for a particular dangerous scene, but it cannot prove the whole film works.
Distributed transactions
A Unit of Work normally covers one database context. It does not automatically make an email provider or Service Bus operation part of the same transaction. We should use an outbox-like process or retry design for external effects, otherwise “saved” can mean only half the operation completed.
Generic Repository and Unit of Work example
Find below a generic implementation which is commonly introduced in an EF6 application,
public interface IRepository<TEntity>
where TEntity : class
{
TEntity Get(int id);
void Add(TEntity entity);
void Remove(TEntity entity);
IQueryable<TEntity> Query();
}
public interface IUnitOfWork
{
int SaveChanges();
}
The implementation is simple,
public sealed class EfRepository<TEntity> : IRepository<TEntity>
where TEntity : class
{
private readonly DbSet<TEntity> set;
public EfRepository(DbContext context)
{
set = context.Set<TEntity>();
}
public TEntity Get(int id)
{
return set.Find(id);
}
public void Add(TEntity entity)
{
set.Add(entity);
}
public void Remove(TEntity entity)
{
set.Remove(entity);
}
public IQueryable<TEntity> Query()
{
return set;
}
}
public sealed class EfUnitOfWork : IUnitOfWork
{
private readonly DbContext context;
public EfUnitOfWork(DbContext context)
{
this.context = context;
}
public int SaveChanges()
{
return context.SaveChanges();
}
}
At first glance it is looking clean, but DbContext is already acting as a Unit of Work and DbSet<TEntity> is already acting like a repository. Returning IQueryable<TEntity> is leaking the query provider, tracking behaviour and database shape to the caller. If the application is using this interface everywhere, changing the persistence approach is still having a large ripple effect.
When the abstraction is helping?
An explicit repository is helping when it is encapsulating a business query, for example GetOpenFundsForValuationDate, and when the query needs a stable contract for many callers. A Unit of Work abstraction is helping when the application operation needs one commit boundary and a test can replace that boundary without creating a database.
It is not helping when every method is only forwarding to DbSet, when the interface is returning IQueryable for every screen, or when tests are mocking EF behaviour which the mock cannot actually reproduce. In our case, we normally keep DbContext inside an application service or a focused repository, and use integration tests for mapping and query correctness.
Must Do and Don’ts
- Must Do: Define a Unit of Work around the business operation, not around every repository method.
- Must Do: Keep
DbContextlifetime per request or per command. - Don’t: Register
DbContextas a singleton, because tracked entities and concurrent requests will create unexpected state. - Don’t: expose
IQueryableat the Web or UI boundary. - Be mindful: A mock repository proves the service decision, it does not prove the SQL query is correct.
If every controller is directly creating DbContext, we are reacting to persistence errors and duplicated queries after they are reaching production. A focused repository and one Unit of Work can make the transaction and test boundary visible proactively. The trade-off is abstraction overhead, so in our case we are keeping DbContext directly when the application is small and introducing a repository only where the business query is having a clear meaning.
How should we decide?
Start with DbContext directly when the application is small and the boundary is already clear. Introduce a repository when a domain aggregate has meaningful access rules, when persistence needs to change, or when a test boundary genuinely helps. Keep the Unit of Work close to the use-case boundary and measure the complexity added.
Wrap up
In this article, we have looked at Repository, Unit of Work, Entity Framework 6, generic repository code, focused interfaces, leakage drawbacks and transaction boundaries. Thanks for reading this article. In the next article, I will walk you through RESTful API resources, verbs and status codes.
Related Posts
What is CQRS - separating reads and writes, and when not to use it?
CQRS explained through commands, handlers, queries, read models, eventual consistency, and the situations where separating reads and writes is unnecessary.
Monolith vs Microservices - should we start with microservices?
Monoliths and microservices compared through modular boundaries, extraction signals, scaling, team ownership, distributed failure, and practical starting criteria for growing teams.
Onion architecture vs N-Tier - which one to choose?
Onion architecture and N-Tier compared through dependency direction, project structure, domain boundaries, dependency injection, and criteria for choosing between them.