Introduction
In our previous tutorials, we learned how to build ASP.NET Core Web APIs, work with Entity Framework Core, implement CRUD operations, and organize application logic.
But as an application grows, placing database queries directly inside controllers or mixing data-access code with business logic can make the application difficult to maintain and test
In this tutorial, we will learn how to implement the Repository Pattern in ASP.NET Core Web API using Entity Framework Core, SQL Server, Dependency Injection, and a clean separation of responsibilities.
What Is the Repository Pattern?
The Repository Pattern is a design pattern that separates data-access logic from the rest of the application.
Instead of allowing controllers or services to directly interact with Entity Framework Core or the database, we create a repository that is responsible for retrieving, inserting, updating, and deleting data.
The repository provides an abstraction over data access. Other parts of the application can work with the repository interface without needing to know the exact details of how data is stored or retrieved.
Without Repository Pattern
In a simple application, a controller may directly use DbContext:
[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
private readonly AppDbContext _context;
public ProductsController(AppDbContext context)
{
_context = context;
}
[HttpGet]
public async Task GetProducts()
{
var products = await _context.Products.ToListAsync();
return Ok(products);
}
}
This approach can work for small applications. However, as more queries, business rules, and operations are added, controllers can become tightly coupled to the database implementation.
With Repository Pattern
We move the data-access operations into a repository and expose them through an interface.
- Controller: Handles HTTP requests and responses.
- Service: Handles application or business logic.
- Repository: Handles data-access operations.
- DbContext: Communicates with the database through Entity Framework Core.
Repository Pattern Architecture
The controller communicates with the service, the service uses the repository abstraction, and the repository implementation works with Entity Framework Core to access the database.
Why Do We Use the Repository Pattern?
1. Separation of Concerns
Each layer has a specific responsibility. Controllers handle HTTP, services handle application logic, and repositories handle data access.
2. Maintainability
When data-access logic is separated, changes become easier to manage. Database-related code does not need to be scattered across multiple controllers.
3. Testability
We can replace a real repository with a fake or mock implementation when testing services without accessing a real database.
4. Reduced Coupling
Services depend on an interface rather than a concrete data-access implementation.
5. Reusability
Repository methods can be reused by multiple services or application workflows when appropriate.
Step 1 – Create the Web API Project
Let's build a Product API using the Repository Pattern.
Using CLI
dotnet new webapi -n RepositoryPatternApi
cd RepositoryPatternApi
Install Entity Framework Core Packages
Install the SQL Server provider and EF Core tools.
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Design
dotnet tool install --global dotnet-ef
If the EF tool is already installed, you can update it instead:
dotnet tool update --global dotnet-ef
Step 2 – Create the Project Structure
Create the following folders and files:
RepositoryPatternApi
│
├── Controllers
│ └── ProductsController.cs
│
├── Data
│ └── AppDbContext.cs
│
├── Models
│ └── Product.cs
│
├── DTOs
│ ├── CreateProductDto.cs
│ ├── UpdateProductDto.cs
│ └── ProductDto.cs
│
├── Repositories
│ ├── IProductRepository.cs
│ └── ProductRepository.cs
│
├── Services
│ ├── IProductService.cs
│ └── ProductService.cs
│
├── Program.cs
└── appsettings.json
We will use DTOs to avoid exposing our database entity directly to API clients.
Step 3 – Create the Product Entity
Create a file named Models/Product.cs.
namespace RepositoryPatternApi.Models;
public class Product
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
public decimal Price { get; set; }
public int Stock { get; set; }
}
This class represents a product stored in the database.
Step 4 – Create DTOs
DTOs (Data Transfer Objects) allow us to control what data enters and leaves the API.
CreateProductDto.cs
using System.ComponentModel.DataAnnotations;
namespace RepositoryPatternApi.DTOs;
public class CreateProductDto
{
[Required]
[StringLength(100)]
public string Name { get; set; } = string.Empty;
[Range(0.01, 1000000)]
public decimal Price { get; set; }
[Range(0, 1000000)]
public int Stock { get; set; }
}
UpdateProductDto.cs
using System.ComponentModel.DataAnnotations;
namespace RepositoryPatternApi.DTOs;
public class UpdateProductDto
{
[Required]
[StringLength(100)]
public string Name { get; set; } = string.Empty;
[Range(0.01, 1000000)]
public decimal Price { get; set; }
[Range(0, 1000000)]
public int Stock { get; set; }
}
ProductDto.cs
namespace RepositoryPatternApi.DTOs;
public class ProductDto
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
public decimal Price { get; set; }
public int Stock { get; set; }
}
Step 5 – Create the DbContext
Create Data/AppDbContext.cs.
using Microsoft.EntityFrameworkCore;
using RepositoryPatternApi.Models;
namespace RepositoryPatternApi.Data;
public class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options)
: base(options)
{
}
public DbSet<Product> Products => Set<Product>();
}
The DbContext represents our database session and is used by Entity Framework Core to perform database operations.
Step 6 – Create the Repository Interface
The repository interface defines the operations that our application needs. It does not contain the actual database implementation.
Create Repositories/IProductRepository.cs.
using RepositoryPatternApi.Models;
namespace RepositoryPatternApi.Repositories;
public interface IProductRepository
{
Task<List<Product>> GetAllAsync();
Task<Product?> GetByIdAsync(int id);
Task<Product> AddAsync(Product product);
Task UpdateAsync(Product product);
Task DeleteAsync(Product product);
}
Notice that the interface exposes product operations without exposing DbContext or SQL queries to the service layer.
Step 7 – Implement the Repository
Now let's implement the interface using Entity Framework Core.
Create Repositories/ProductRepository.cs.
using Microsoft.EntityFrameworkCore;
using RepositoryPatternApi.Data;
using RepositoryPatternApi.Models;
namespace RepositoryPatternApi.Repositories;
public class ProductRepository : IProductRepository
{
private readonly AppDbContext _context;
public ProductRepository(AppDbContext context)
{
_context = context;
}
public async Task<List<Product>> GetAllAsync()
{
return await _context.Products
.AsNoTracking()
.ToListAsync();
}
public async Task<Product?> GetByIdAsync(int id)
{
return await _context.Products
.AsNoTracking()
.FirstOrDefaultAsync(p => p.Id == id);
}
public async Task<Product>> AddAsync(Product product)
{
await _context.Products.AddAsync(product);
await _context.SaveChangesAsync();
return product;
}
public async Task UpdateAsync(Product product)
{
var existingProduct = await _context.Products
.FirstOrDefaultAsync(p => p.Id == product.Id);
if (existingProduct is null)
{
throw new KeyNotFoundException(
$"Product with ID {product.Id} was not found.");
}
existingProduct.Name = product.Name;
existingProduct.Price = product.Price;
existingProduct.Stock = product.Stock;
await _context.SaveChangesAsync();
}
public async Task DeleteAsync(Product product)
{
_context.Products.Remove(product);
await _context.SaveChangesAsync();
}
}
Important: In the AddAsync method, the return type should be Task<Product>. If you copy the code, ensure the declaration is exactly:
public async Task<Product> AddAsync(Product product)
What is happening here?
GetAllAsync()retrieves all products.GetByIdAsync()retrieves a product by ID.AddAsync()inserts a new product.UpdateAsync()finds and updates an existing product.DeleteAsync()removes a product.AsNoTracking()is used for read-only queries to avoid unnecessary change tracking.
We use asynchronous EF Core operations to avoid blocking the request thread while waiting for database I/O.
Step 8 – Create the Service Interface
The service layer is responsible for application logic. It uses the repository rather than directly accessing the DbContext.
Create Services/IProductService.cs.
using RepositoryPatternApi.DTOs;
namespace RepositoryPatternApi.Services;
public interface IProductService
{
Task<List<ProductDto>> GetAllAsync();
Task<ProductDto?> GetByIdAsync(int id);
Task<ProductDto> CreateAsync(CreateProductDto dto);
Task UpdateAsync(int id, UpdateProductDto dto);
Task DeleteAsync(int id);
}
Step 9 – Implement the Service
Create Services/ProductService.cs.
using RepositoryPatternApi.DTOs;
using RepositoryPatternApi.Models;
using RepositoryPatternApi.Repositories;
namespace RepositoryPatternApi.Services;
public class ProductService : IProductService
{
private readonly IProductRepository _repository;
public ProductService(IProductRepository repository)
{
_repository = repository;
}
public async Task<List<ProductDto>> GetAllAsync()
{
var products = await _repository.GetAllAsync();
return products.Select(MapToDto).ToList();
}
public async Task<ProductDto?> GetByIdAsync(int id)
{
var product = await _repository.GetByIdAsync(id);
return product is null ? null : MapToDto(product);
}
public async Task<ProductDto>> CreateAsync(CreateProductDto dto)
{
var product = new Product
{
Name = dto.Name,
Price = dto.Price,
Stock = dto.Stock
};
var createdProduct = await _repository.AddAsync(product);
return MapToDto(createdProduct);
}
public async Task UpdateAsync(int id, UpdateProductDto dto)
{
var existingProduct = await _repository.GetByIdAsync(id);
if (existingProduct is null)
{
throw new KeyNotFoundException(
$"Product with ID {id} was not found.");
}
existingProduct.Name = dto.Name;
existingProduct.Price = dto.Price;
existingProduct.Stock = dto.Stock;
await _repository.UpdateAsync(existingProduct);
}
public async Task DeleteAsync(int id)
{
var existingProduct = await _repository.GetByIdAsync(id);
if (existingProduct is null)
{
throw new KeyNotFoundException(
$"Product with ID {id} was not found.");
}
await _repository.DeleteAsync(existingProduct);
}
private static ProductDto MapToDto(Product product)
{
return new ProductDto
{
Id = product.Id,
Name = product.Name,
Price = product.Price,
Stock = product.Stock
};
}
}
The service maps DTOs to entities and entities to DTOs. It also handles the application flow and checks whether a product exists before updating or deleting it.
Step 10 – Create the Products Controller
The controller handles HTTP requests and uses the service. It does not directly interact with Entity Framework Core.
Create Controllers/ProductsController.cs.
using Microsoft.AspNetCore.Mvc;
using RepositoryPatternApi.DTOs;
using RepositoryPatternApi.Services;
namespace RepositoryPatternApi.Controllers;
[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
private readonly IProductService _service;
public ProductsController(IProductService service)
{
_service = service;
}
[HttpGet]
public async Task<ActionResult<List<ProductDto>>> GetAll()
{
var products = await _service.GetAllAsync();
return Ok(products);
}
[HttpGet("{id:int}")]
public async Task<ActionResult<ProductDto>> GetById(int id)
{
var product = await _service.GetByIdAsync(id);
if (product is null)
return NotFound();
return Ok(product);
}
[HttpPost]
public async Task<ActionResult<ProductDto>> Create(
CreateProductDto dto)
{
var product = await _service.CreateAsync(dto);
return CreatedAtAction(
nameof(GetById),
new { id = product.Id },
product);
}
[HttpPut("{id:int}")]
public async Task<IActionResult> Update(
int id,
UpdateProductDto dto)
{
try
{
await _service.UpdateAsync(id, dto);
return NoContent();
}
catch (KeyNotFoundException)
{
return NotFound();
}
}
[HttpDelete("{id:int}")]
public async Task<IActionResult> Delete(int id)
{
try
{
await _service.DeleteAsync(id);
return NoContent();
}
catch (KeyNotFoundException)
{
return NotFound();
}
}
}
For a production application, exception handling should generally be centralized using exception-handling middleware or an exception handler instead of repeating try/catch blocks in every controller action.
Step 11 – Configure the Connection String
Open appsettings.json and add your SQL Server connection string.
{
"ConnectionStrings": {
"DefaultConnection": "Server=localhost;Database=RepositoryPatternDb;Trusted_Connection=True;TrustServerCertificate=True;"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}
Update the connection string based on your SQL Server installation. For SQL Server Express, your server may be something like localhost\\SQLEXPRESS.
For applications deployed to production, do not store sensitive database credentials directly in source-controlled configuration files. Use secure configuration providers, environment variables, or a secret manager.
Step 12 – Configure Dependency Injection in Program.cs
ASP.NET Core uses Dependency Injection to create and provide required objects to classes.
Open Program.cs.
using Microsoft.EntityFrameworkCore;
using RepositoryPatternApi.Data;
using RepositoryPatternApi.Repositories;
using RepositoryPatternApi.Services;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(
builder.Configuration.GetConnectionString("DefaultConnection")));
builder.Services.AddScoped<IProductRepository, ProductRepository>();
builder.Services.AddScoped<IProductService, ProductService>();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
Understanding the registrations
builder.Services.AddScoped<IProductRepository, ProductRepository>();
builder.Services.AddScoped<IProductService, ProductService>();
These registrations tell the dependency injection container:
- Whenever
IProductRepositoryis requested, create aProductRepository. - Whenever
IProductServiceis requested, create aProductService. - Use the scoped lifetime, which normally creates one instance per HTTP request scope.
Step 13 – Create the Database
We are using the Code First approach with Entity Framework Core migrations.
Run the following commands from the project folder:
PowerShell
dotnet ef migrations add InitialCreate
dotnet ef database update
CMD
dotnet ef migrations add InitialCreate
dotnet ef database update
These commands create a migration and apply it to the database.
Step 14 – Run the API
dotnet run
Open the Swagger URL shown in the console, if Swagger is enabled in your development environment.
Step 15 – Test the API
1. Get All Products
HTTP Method: GET
GET /api/products
2. Get Product by ID
HTTP Method: GET
GET /api/products/1
3. Create Product
HTTP Method: POST
Request Body:
{
"name": "Laptop",
"price": 75000,
"stock": 10
}
Expected response: 201 Created
4. Update Product
HTTP Method: PUT
PUT /api/products/1
Request Body:
{
"name": "Gaming Laptop",
"price": 85000,
"stock": 8
}
Expected response: 204 No Content
5. Delete Product
HTTP Method: DELETE
DELETE /api/products/1
Expected response: 204 No Content
Testing with PowerShell
GET All Products
Invoke-RestMethod -Uri "https://localhost:7001/api/products" -Method GET
GET by ID
Invoke-RestMethod -Uri "https://localhost:7001/api/products/1" -Method GET
POST Product
$body = @{
name = "Laptop"
price = 75000
stock = 10
} | ConvertTo-Json
Invoke-RestMethod `
-Uri "https://localhost:7001/api/products" `
-Method POST `
-ContentType "application/json" `
-Body $body
PUT Product
$body = @{
name = "Gaming Laptop"
price = 85000
stock = 8
} | ConvertTo-Json
Invoke-RestMethod `
-Uri "https://localhost:7001/api/products/1" `
-Method PUT `
-ContentType "application/json" `
-Body $body
DELETE Product
Invoke-RestMethod `
-Uri "https://localhost:7001/api/products/1" `
-Method DELETE
Note: Replace the example port with the HTTPS port generated by your application.
Testing with CMD using curl
GET All Products
curl -k -X GET "https://localhost:7001/api/products"
GET by ID
curl -k -X GET "https://localhost:7001/api/products/1"
POST Product
curl -k -X POST "https://localhost:7001/api/products" -H "Content-Type: application/json" -d "{\"name\":\"Laptop\",\"price\":75000,\"stock\":10}"
PUT Product
curl -k -X PUT "https://localhost:7001/api/products/1" -H "Content-Type: application/json" -d "{\"name\":\"Gaming Laptop\",\"price\":85000,\"stock\":8}"
DELETE Product
curl -k -X DELETE "https://localhost:7001/api/products/1"
Note: The -k option skips certificate validation and is useful only for local development with a development HTTPS certificate. Do not use it as a security workaround in production.
Repository Pattern Request Flow
Repository Pattern vs Direct DbContext Usage
| Direct DbContext | Repository Pattern |
|---|---|
| Controller or service accesses DbContext directly | Data-access logic is isolated in repository implementations |
| Database queries may spread throughout the application | Queries can be centralized within repository methods |
| Testing may require more database setup | Repository interfaces can be replaced with test doubles |
| Can be simpler for small CRUD applications | Can add structure and abstraction to larger applications |
| Fewer layers and less boilerplate | More interfaces, classes, and code to maintain |
Important: The Repository Pattern is not mandatory for every ASP.NET Core application. Entity Framework Core already provides many repository-like capabilities through DbSet and DbContext. In smaller applications, directly using DbContext in services may be perfectly reasonable. Choose the pattern based on the complexity, maintainability, and testing needs of your application.
Common Mistakes When Using Repository Pattern
1. Putting Business Logic Inside the Repository
Repositories should primarily handle data access. Business rules such as calculating discounts or determining order eligibility generally belong in the service or domain layer.
2. Returning IQueryable Everywhere
Exposing IQueryable from a repository can leak query-provider details and allow calling layers to construct database queries. It can be appropriate in some designs, but it weakens the repository abstraction if used without care.
3. Creating a Generic Repository for Everything
A generic repository can reduce repeated CRUD code, but it may become overly abstract or fail to express the specific operations a domain needs. Use abstractions that add genuine value.
4. Ignoring Async Operations
Database operations should generally use asynchronous methods such as ToListAsync, FirstOrDefaultAsync, and SaveChangesAsync in web applications.
5. Returning Database Entities Directly
Returning entities from API endpoints can expose internal fields or make the API contract dependent on the database model. DTOs help control the request and response structure.
6. Duplicating Repository Logic
Keep repository methods focused and reusable. Avoid implementing the same query logic differently in multiple places when it can be centralized appropriately.
Best Practices
- Use interfaces to define repository contracts.
- Keep controllers focused on HTTP concerns.
- Place application logic in services or domain components.
- Use DTOs for API input and output.
- Use asynchronous database operations.
- Use
AsNoTracking()for suitable read-only queries. - Register repositories and services with Dependency Injection.
- Use appropriate DI lifetimes. Repositories using EF Core DbContext are typically scoped.
- Handle exceptions consistently using centralized exception handling.
- Do not add abstractions merely for the sake of adding more layers.
- Test service logic separately from data-access integration tests.
Practical Exercise
Now that we have built the Product Repository, try extending it.
- Add a category property to Product.
- Create a repository method to get products by category.
- Implement a method to find products below a specified price.
- Add a search method to find products by name.
- Implement sorting by price.
- Add pagination to the product list.
- Write unit tests for the service using a fake repository.
These exercises will help you understand how the Repository Pattern can support more complex data-access requirements.
Key Takeaways
- The Repository Pattern separates data-access logic from other application layers.
- Repositories expose operations through interfaces.
- Entity Framework Core can be used inside repository implementations.
- Services can depend on repository abstractions.
- Controllers should focus on handling HTTP requests and responses.
- Repository abstractions can improve testability and maintainability when used appropriately.
- Repository Pattern is a design choice, not a mandatory requirement for every API.
What's Next?
In the next tutorial, we will learn about Unit Testing with xUnit in ASP.NET Core Web API, where we will test application logic, use test cases, and understand how unit tests help us catch problems before deploying our application.
Keep practicing, keep building, and keep improving your backend development skills!
Skills Tutorials – Learn • Build • Grow Together
Continue learning with our 30-day .NET Core Web API series.