0
0
CsharpConceptBeginner · 4 min read

Repository Pattern in C#: What It Is and How It Works

The repository pattern in C# is a design approach that separates data access logic from business logic by using a repository class to handle data operations. It acts like a middleman between your application and the data source, making code easier to manage and test.
⚙️

How It Works

Imagine you have a store where you keep all your books. Instead of searching the entire store every time you want a book, you ask the storekeeper who knows exactly where each book is. The repository pattern works like that storekeeper. It hides the details of how data is stored and retrieved, so your main program doesn't have to worry about it.

In C#, this means you create a repository class that handles all the operations like adding, removing, or finding data. Your application talks only to this repository, not directly to the database or data source. This separation makes your code cleaner and easier to change later without breaking other parts.

💻

Example

This example shows a simple repository for managing a list of books. It demonstrates how to add and get books without exposing the data storage details.

csharp
using System;
using System.Collections.Generic;
using System.Linq;

// Book entity
public class Book
{
    public int Id { get; set; }
    public string Title { get; set; }
}

// Repository interface
public interface IBookRepository
{
    void Add(Book book);
    Book GetById(int id);
    IEnumerable<Book> GetAll();
}

// Repository implementation
public class BookRepository : IBookRepository
{
    private readonly List<Book> _books = new List<Book>();

    public void Add(Book book)
    {
        _books.Add(book);
    }

    public Book GetById(int id)
    {
        return _books.FirstOrDefault(b => b.Id == id);
    }

    public IEnumerable<Book> GetAll()
    {
        return _books;
    }
}

// Usage
public class Program
{
    public static void Main()
    {
        IBookRepository repository = new BookRepository();

        repository.Add(new Book { Id = 1, Title = "C# Basics" });
        repository.Add(new Book { Id = 2, Title = "Design Patterns" });

        var book = repository.GetById(2);
        Console.WriteLine($"Book found: {book.Title}");
    }
}
Output
Book found: Design Patterns
🎯

When to Use

Use the repository pattern when you want to keep your data access code separate from your business logic. This is especially helpful in larger projects where you might change the database or data source later. It also makes testing easier because you can replace the repository with a fake one during tests.

For example, if you build an app that talks to a database, using a repository lets you switch from one database type to another without changing your main code. It also helps when multiple developers work on the project by keeping responsibilities clear.

Key Points

  • The repository pattern abstracts data access behind a simple interface.
  • It improves code organization by separating concerns.
  • It makes unit testing easier by allowing mock repositories.
  • It helps manage changes in data storage without affecting business logic.

Key Takeaways

The repository pattern separates data access from business logic for cleaner code.
It acts as a middleman between your app and data sources, hiding complexity.
Use it to make your code easier to maintain, test, and adapt to changes.
Repositories provide a consistent interface for data operations.
It is especially useful in larger or evolving projects with complex data needs.