Implementing Repository Pattern in ASP.NET Core

Implementing Repository Pattern in ASP.NET Core

21 Jun 2024
Beginner
66 Views
9 min read

Repository Pattern in ASP.NET Core

In software development, managing data access can become complex quickly. One way to simplify and organize this aspect of your application is to use the Repository Pattern. This design helps manage and maintain data access.

In this ASP.NET Core Tutorial, we will talk about the Repository Pattern in ASP.NET Core, its functioning, and its importance. If in case you need more detailed information about other ASP.NET-related topics, mddake sure you have enrolled in our ASP.NET Core Certification Training.

What is a Repository Pattern?

The Repository Pattern is a design, that acts like a middleman between the application and data source. The main aim is to have a cleaner code that is easy to maintain and reuse both logic and data access.

Repository Pattern Interface

To implement the Repository Pattern, we first define an interface that outlines the methods for accessing data. This interface will represent the contract that any repository class must fulfill. A simple example is shown below: 

public interface IRepository<T>
{
    IEnumerable<T> GetAll();
    T GetById(int id);
    void Add(T entity);
    void Update(T entity);
    void Delete(int id);
}

Any repository class must carry out the basic CRUD operations (Create, Read, Update, Delete) defined by this interface.

Read More: ASP.NET Core And Entity Framework Core CRUD Operations

Core Principles of the Repository Pattern

The core principles of the Repository Pattern are as follows:
  1. Abstraction- Separates the data access logic from the business logic.
  2. Encapsulation-Encapsulates the logic required to access data sources.
  3. Testability-Makes unit testing easier by allowing you to mock data access layers.
  4. DRY (Don't Repeat Yourself)-Reduces code duplication by centralizing data access logic.

Repository Pattern - SQL Server Implementation

Let's dive into an example of implementing the Repository Pattern with SQL Server in an ASP.NET application. We will start by creating our data models.

1.) Creating Models

First, we define our data models that will represent the database tables. For example, let's create a 'Product' model:
public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
}

2.) Context Class and the Database Connection

Next, we create a context class that represents a session with the database. This class derives from DbContext and includes DbSet properties for each model:
public class ApplicationDbContext : DbContext
{
    public ApplicationDbContext(DbContextOptions options) : base(options) { }

    public DbSet Products { get; set; }
}

3.) Repository Pattern Logic

With our models and context in place, we can now implement the repository logic. We start by creating a repository class that implements the IRepository interface:
public class Repository<T> : IRepository<T> where T : class
{
    private readonly ApplicationDbContext _context;
    private readonly DbSet<T> _dbSet;

    public Repository(ApplicationDbContext context)
    {
        _context = context;
        _dbSet = _context.Set<T>();
    }

    public IEnumerable<T> GetAll()
    {
        return _dbSet.ToList();
    }

    public T GetById(int id)
    {
        return _dbSet.Find(id);
    }

    public void Add(T entity)
    {
        _dbSet.Add(entity);
        _context.SaveChanges();
    }

    public void Update(T entity)
    {
        _dbSet.Attach(entity);
        _context.Entry(entity).State = EntityState.Modified;
        _context.SaveChanges();
    }

    public void Delete(int id)
    {
        var entity = _dbSet.Find(id);
        _dbSet.Remove(entity);
        _context.SaveChanges();
    }
}

4.) Repository User Classes

Now, let's see how we can use this repository in our application. For example, in a controller:
public class ProductsController : Controller
{
    private readonly IRepository<Product> _productRepository;

    public ProductsController(IRepository<Product> productRepository)
    {
        _productRepository = productRepository;
    }

    public IActionResult Index()
    {
        var products = _productRepository.GetAll();
        return View(products);
    }

    // Other action methods for Create, Edit, Delete, etc.
}

5.) Creating a Repository Wrapper

To further enhance flexibility, we can create a repository wrapper that consolidates multiple repositories. This wrapper can manage instances of different repositories and simplify their usage.
public interface IRepositoryWrapper
{
    IRepository<Product> Product { get; }
    // Add other repositories here
    void Save();
}

public class RepositoryWrapper : IRepositoryWrapper
{
    private readonly ApplicationDbContext _context;
    private IRepository<Product> _productRepository;

    public RepositoryWrapper(ApplicationDbContext context)
    {
        _context = context;
    }

    public IRepository<Product> Product
    {
        get
        {
            if (_productRepository == null)
            {
                _productRepository = new Repository<Product>(_context);
            }
            return _productRepository;
        }
    }

    public void Save()
    {
        _context.SaveChanges();
    }
}

Benefits of Repository Pattern

The Repository Pattern offers several benefits, including:
  • Code Reusability- By centralizing data access logic, you can reuse the same repository methods across different parts of your application.
  • Ease of Testing—The abstraction allows you to mock the data layer easily, making unit tests more straightforward and reliable.
  • Separation of Concerns- By keeping the data access logic separate from the business logic, the codebase is cleaner and more organized.
  • Consistency- Guarantees that all data accesses across an application exhibit consistent patterns, reducing mistakes and promoting dependability.
Conclusion
This article talks about the Repository Pattern in ASP.NET Core and why developers find it useful for managing their data access logic, making their code clean and performance-driven thus making development easier. Check out our ASP.NET Core Course to get more insights on ASP.NET Core.

Read More: ASP.NET Core Interview Questions and Answers

FAQs

Q1. What is repository pattern in asp net core?

Repository Pattern in ASP.NET Core is a design pattern that enables the usage of CRUD operations to separate the data logic from the business logic

Q2. What are repository patterns?

They are the design patterns used for separating business logic from data access logic, enabling the data manipulation and retrieval in a single place.

Q3. What is repository types?

Repository types are the different ways how we can structure the repositories and use them in an application. Common types are:
  • Generic repositories
  • Specific repositories
  • Composite repositories
Share Article

Live Classes Schedule

Our learn-by-building-project method enables you to build practical/coding experience that sticks. 95% of our learners say they have confidence and remember more when they learn by building real world projects.
ASP.NET Core Certification Training Jul 17 MON, WED, FRI
Filling Fast
07:00AM to 08:30AM (IST)
Get Details
Angular Certification Course Jul 20 SAT, SUN
Filling Fast
06:00PM to 08:00PM (IST)
Get Details
Azure Developer Certification Training Jul 28 SAT, SUN
Filling Fast
10:00AM to 12:00PM (IST)
Get Details
ASP.NET Core Certification Training Jul 28 SAT, SUN
Filling Fast
07:00AM to 09:00AM (IST)
Get Details
Angular Certification Course Aug 11 SAT, SUN
Filling Fast
09:30AM to 11:30AM (IST)
Get Details
ASP.NET Core Project Aug 24 SAT, SUN
Filling Fast
07:00AM to 09:00AM (IST)
Get Details

Can't find convenient schedule? Let us know

About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

Shailendra Chauhan is the Founder and CEO at ScholarHat by DotNetTricks which is a brand when it comes to e-Learning. He provides training and consultation over an array of technologies like Cloud, .NET, Angular, React, Node, Microservices, Containers and Mobile Apps development. He has been awarded Microsoft MVP 8th time in a row (2016-2023). He has changed many lives with his writings and unique training programs. He has a number of most sought-after books to his name which has helped job aspirants in cracking tough interviews with ease.
Self-paced Membership
  • 22+ Video Courses
  • 800+ Hands-On Labs
  • 400+ Quick Notes
  • 55+ Skill Tests
  • 45+ Interview Q&A Courses
  • 10+ Real-world Projects
  • Career Coaching Sessions
  • Email Support
Upto 60% OFF
Know More
Accept cookies & close this