Sunday, 6 August 2023

Repository Design pattern in c#

The repository pattern is a popular design pattern in C# that provides a way to manage data access and manipulation in a consistent and maintainable manner. The repository pattern is used to separate the application's business logic from the data access layer. Here is an example implementation of the repository pattern in C#


1. Define an interface for the repository:


public interface IRepository where T : class
{
    IEnumerable GetAll();
    T GetById(int id);
    void Add(T entity);
    void Update(T entity);
    void Delete(T entity);
}

2. Create a concrete implementation of the repository interface:


public class Repository : IRepository where T : class
{
    private readonly DbContext _context;
    private readonly DbSet _dbSet;

    public Repository(DbContext context)
    {
        _context = context;
        _dbSet = context.Set();
    }

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

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

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

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

    public void Delete(T entity)
    {
        _dbSet.Remove(entity);
    }
}

3. Use the repository in your application:


public class MyService
{
    private readonly IRepository _repository;

    public MyService(IRepository repository)
    {
        _repository = repository;
    }

    public IEnumerable GetAll()
    {
        return _repository.GetAll();
    }

    public MyEntity GetById(int id)
    {
        return _repository.GetById(id);
    }

    public void Add(MyEntity entity)
    {
        _repository.Add(entity);
    }

    public void Update(MyEntity entity)
    {
        _repository.Update(entity);
    }

    public void Delete(MyEntity entity)
    {
        _repository.Delete(entity);
    }
}


By using the repository pattern, you can abstract away the details of data access and manipulation, and write cleaner, more maintainable code that is easier to test and update.


No comments:

Post a Comment