Tutorials Entity Framework Core Tutorial
Repository Pattern with EF Core
Repository Pattern with EF Core: free step-by-step lesson with examples, common mistakes, and interview tips — part of Entity Framework Core Tutorial on Toolliyo Academy.
On this page
Entity Framework Core Tutorial · Lesson 51 of 100
Repository Pattern with EF Core
Beginner ✓ → Intermediate ✓ → Advanced → Professional
Advanced · 3 — Production skills · ~6 min · Module 6: Advanced EF Core
What is this?
The repository pattern wraps DbSet access behind interfaces like IProductRepository — hiding EF details from application services.
Why should you care?
ShopNest ProductService should depend on IProductRepository, not ShopNestDbContext directly — easier testing and clearer boundaries.
See it live — copy this example
Paste into a .NET project with EF Core packages, then run with LocalDB/SQL Server (dotnet ef / dotnet run).
public interface IProductRepository
{
Task<Product?> GetBySkuAsync(string sku, CancellationToken ct);
Task AddAsync(Product product, CancellationToken ct);
}
public class ProductRepository(ShopNestDbContext db) : IProductRepository
{
public Task<Product?> GetBySkuAsync(string sku, CancellationToken ct) =>
db.Products.FirstOrDefaultAsync(p => p.Sku == sku, ct);
public Task AddAsync(Product product, CancellationToken ct) =>
db.Products.AddAsync(product, ct).AsTask();
}
What happened?
- Repository delegates to DbContext internally.
- Service calls interface; SaveChangesAsync typically lives in unit of work or service after multiple repository ops.
Practice next
- Extract product queries from service into ProductRepository.
- Register IProductRepository as Scoped in DI.
- Keep repositories focused — avoid generic IRepository
for everything. - Add ListPublishedByCategoryAsync with encapsulated Include logic.
- Fake repository returning fixed Product for service unit test.
Remember
Repository abstracts data access behind interfaces. Enables mocking in unit tests. Use when indirection pays for complexity.
ShopNest catalog service
ProductService unit tests mock IProductRepository for pricing rules without database.
Outcome: Fast CI tests for business logic separate from SQL integration.
Interview prep for this lesson
Practice these questions aloud after reading—each links to a full structured answer.
Sign in to ask a question or upvote helpful answers.
No questions yet — be the first to ask!