The Repository design pattern is a software design pattern that provides an abstraction layer between the application and the data source (such as a database, file system, or external API). It encapsulates the data access logic and provides a clean and consistent interface for performing CRUD (Create, Read, Update, Delete) operations on data entities.
The Repository pattern typically consists of an interface that defines the contract for data access operations and a concrete implementation that provides the actual implementation of those operations. The repository acts as a mediator between the application and the data source, shielding the application from the underlying data access details.
Here's an example of a repository interface:
public interface IRepository<T> { T GetById(int id); IEnumerable<T> GetAll(); void Add(T entity); void Update(T entity); void Delete(T entity); }
And here's an example of a repository implementation using Entity Framework in C#:
public class Repository<T> : IRepository<T> where T : class { private readonly DbContext _context; private readonly DbSet<T> _dbSet; public Repository(DbContext context) { _context = context; _dbSet = context.Set<T>(); } public T GetById(int id) { return _dbSet.Find(id); } public IEnumerable<T> GetAll() { return _dbSet.ToList(); } public void Add(T entity) { _dbSet.Add(entity); _context.SaveChanges(); } public void Update(T entity) { _context.Entry(entity).State = EntityState.Modified; _context.SaveChanges(); } public void Delete(T entity) { _dbSet.Remove(entity); _context.SaveChanges(); } }
In this example, the IRepository
interface defines the common data access operations like GetById
, GetAll
, Add
, Update
, and Delete
. The Repository
class implements this interface using Entity Framework, providing the actual implementation of these operations.
The repository implementation uses a DbContext
to interact with the database, and a DbSet<T>
to represent the collection of entities of type T
. The methods perform the corresponding operations on the DbSet<T>
and save changes to the database using the DbContext
.
The Repository pattern helps decouple the application from the specific data access technology and provides a clear separation of concerns. It improves testability, code maintainability, and reusability by centralizing the data access logic. It also allows for easier swapping of data access implementations, such as changing from Entity Framework to a different ORM or data source, without affecting the application code that uses the repository interface.
No comments:
Post a Comment