Repository Pattern in C#

3 min read 10 months ago
Published on Oct 05, 2024 This response is partially generated with the help of AI. It may contain inaccuracies.

Table of Contents

Introduction

This tutorial will guide you through implementing the Repository Pattern in C#. The Repository Pattern is a design pattern that provides a way to encapsulate the storage, retrieval, and query of data, making your application easier to manage and test. By the end of this tutorial, you will have a solid understanding of how to use this pattern in your own projects.

Step 1: Create the Model

Before implementing the Repository Pattern, you need to define the data model that will be used.

  1. Define the Entity Class:
    • Create a class that represents the data structure. For example, if you're working with a Product, define the class with properties.
    public class Product
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public decimal Price { get; set; }
    }
    

Step 2: Create the Repository Interface

The next step is to create an interface that outlines the methods for data operations.

  1. Define the Interface:
    • Create an interface that includes CRUD operations (Create, Read, Update, Delete).
    public interface IProductRepository
    {
        void Add(Product product);
        Product GetById(int id);
        IEnumerable<Product> GetAll();
        void Update(Product product);
        void Delete(int id);
    }
    

Step 3: Implement the Repository

Now, you will implement the repository interface to handle database operations.

  1. Create the Repository Class:
    • Implement the methods defined in the interface, using your chosen data access technology (like Entity Framework).
    public class ProductRepository : IProductRepository
    {
        private readonly DbContext _context;
    
        public ProductRepository(DbContext context)
        {
            _context = context;
        }
    
        public void Add(Product product)
        {
            _context.Products.Add(product);
            _context.SaveChanges();
        }
    
        public Product GetById(int id)
        {
            return _context.Products.Find(id);
        }
    
        public IEnumerable<Product> GetAll()
        {
            return _context.Products.ToList();
        }
    
        public void Update(Product product)
        {
            _context.Products.Update(product);
            _context.SaveChanges();
        }
    
        public void Delete(int id)
        {
            var product = GetById(id);
            if (product != null)
            {
                _context.Products.Remove(product);
                _context.SaveChanges();
            }
        }
    }
    

Step 4: Use the Repository in Your Application

With the repository implemented, you can now use it in your application.

  1. Inject the Repository:
    • Use dependency injection to include the repository in your services or controllers.
    public class ProductService
    {
        private readonly IProductRepository _productRepository;
    
        public ProductService(IProductRepository productRepository)
        {
            _productRepository = productRepository;
        }
    
        public void CreateProduct(string name, decimal price)
        {
            var product = new Product { Name = name, Price = price };
            _productRepository.Add(product);
        }
    }
    

Conclusion

You have successfully implemented the Repository Pattern in C#. You defined a model, created a repository interface, implemented the repository, and injected it into your application. This pattern helps separate concerns and makes your code more maintainable and testable.

Next steps could include:

  • Exploring Unit Testing with your repository.
  • Implementing additional patterns such as Unit of Work.
  • Learning more about Entity Framework for data access.