What is C# Repository Design Pattern

The repository pattern in C# is a design pattern that provides a separation between the data access layer and the business logic layer of an application. The goal of the repository pattern is to create a unified interface to access data, regardless of the underlying data source.

Repository Design Pattern

A repository is essentially a collection of objects that can be queried and updated. It provides a higher level of abstraction over the data source and can simplify the code by centralizing the data access logic.

Here's a basic example of a repository pattern in C#:

public interface IStudentRepository { IEnumerable<Student> GetAll(); Student GetById(int id); void Add(Student student); void Update(Student student); void Delete(int id); }
public class StudentRepository : IStudentRepository { private readonly DatabaseContext _context; public StudentRepository(DatabaseContext context) { _context = context; } public IEnumerable<Student> GetAll() { return _context.Students.ToList(); } public Student GetById(int id) { return _context.Students.Find(id); } public void Add(Student student) { _context.Students.Add(student); _context.SaveChanges(); } public void Update(Student student) { _context.Students.Update(student); _context.SaveChanges(); } public void Delete(int id) { var student = _context.Students.Find(id); _context.Students.Remove(student); _context.SaveChanges(); } }

In this example, the IStudentRepository interface defines the methods that the repository should provide. The StudentRepository class implements the IStudentRepository interface and provides the actual implementation of the data access logic.

The StudentRepository class uses a DatabaseContext object to access the data source. The DatabaseContext could be an Entity Framework context, or any other data access technology.

Through the repository pattern, you can rule out duplication of data access code in one place and thus working structural errors of your application. This in turn simplifies the data access logic maintenance and may also make the technology switch (i.e. a different data technology) unnecessary if this ever happens.

Entity Framework context

The Entity Framework context is an object that acts as a bridge between the application and the database. It represents the state of the database, tracks changes made to the data, and is responsible for persisting the changes back to the database.

The context is an implementation of the Unit of Work pattern and provides a single point of access to the database. This can simplify the code by centralizing the data access logic and avoiding duplicated code throughout the application.