Introduction
When building web applications with ASP.NET Core, developers often need to interact with a database. While Entity Framework Core allows direct database operations, using raw database queries in controllers or services can make your code messy, tightly coupled, and hard to maintain.
This is where the Repository Pattern comes into play. It provides a clean, organized way to manage data access, separating the database logic from the business logic.
This article explains the repository pattern in a simple, step-by-step way, including why it is useful, how it works, and how to implement it in ASP.NET Core.
What is the Repository Pattern?
The repository pattern is a design pattern that abstracts the data access logic and provides a centralized way to interact with the database.
Key Principles
Separation of Concerns: Controllers or services do not directly access the database.
Abstraction: The rest of the application only interacts with repository interfaces.
Testability: Makes unit testing easier because repositories can be mocked.
Think of a repository as a middleman between your application and the database.
Why Use the Repository Pattern?
Using the repository pattern has several advantages:
Clean Code: Keeps controllers and services simple.
Reusability: Common database operations can be reused across multiple controllers.
Maintainability: Changes in the database layer do not affect business logic.
Unit Testing: Allows mocking repositories without connecting to the actual database.
Consistency: Ensures consistent data access patterns across the application.
Basic Structure of Repository Pattern
A typical implementation includes:
Repository Interface: Defines the methods for data access.
Repository Implementation: Contains actual database logic using Entity Framework Core or other ORMs.
Service or Controller: Uses the repository to perform operations.
Step 1: Create the Model
Suppose we have a User model:
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
}
Step 2: Create the Repository Interface
Create an interface IUserRepository:
using System.Collections.Generic;
using System.Threading.Tasks;
public interface IUserRepository
{
Task<IEnumerable<User>> GetAllUsersAsync();
Task<User> GetUserByIdAsync(int id);
Task AddUserAsync(User user);
Task UpdateUserAsync(User user);
Task DeleteUserAsync(int id);
}
This defines all the operations we want to perform on users.
Notice that the interface does not include database-specific code, just method signatures.
Step 3: Implement the Repository
Create a class UserRepository:
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Threading.Tasks;
public class UserRepository : IUserRepository
{
private readonly AppDbContext _context;
public UserRepository(AppDbContext context)
{
_context = context;
}
public async Task<IEnumerable<User>> GetAllUsersAsync()
{
return await _context.Users.ToListAsync();
}
public async Task<User> GetUserByIdAsync(int id)
{
return await _context.Users.FindAsync(id);
}
public async Task AddUserAsync(User user)
{
await _context.Users.AddAsync(user);
await _context.SaveChangesAsync();
}
public async Task UpdateUserAsync(User user)
{
_context.Users.Update(user);
await _context.SaveChangesAsync();
}
public async Task DeleteUserAsync(int id)
{
var user = await _context.Users.FindAsync(id);
if (user != null)
{
_context.Users.Remove(user);
await _context.SaveChangesAsync();
}
}
}

Join the conversation! Your thoughts help the community grow.