repository class in csharp

In C#, Repository is a design pattern that is used to abstract the data access layer of an application. It is a class that is responsible for performing CRUD (Create, Read, Update, Delete) operations on a particular domain entity or a set of entities, and hides the logic of retrieving and storing data from the application code.

Here's an example of a repository class in C#, using Entity Framework to interact with the database:

main.cs
public interface IRepository<TEntity> where TEntity : class 
{
    TEntity Get(int id);
    IQueryable<TEntity> GetAll();
    void Add(TEntity entity);
    void Update(TEntity entity);
    void Delete(TEntity entity);
}

public class Repository<TEntity> : IRepository<TEntity> where TEntity : class
{
    private readonly DbContext _context;
    private readonly DbSet<TEntity> _entities;

    public Repository(DbContext context)
    {
        _context = context;
        _entities = context.Set<TEntity>();
    }

    public TEntity Get(int id)
    {
        return _entities.Find(id);
    }

    public IQueryable<TEntity> GetAll()
    {
        return _entities.AsQueryable();
    }

    public void Add(TEntity entity)
    {
        _entities.Add(entity);
    }

    public void Update(TEntity entity)
    {
        _entities.Update(entity);
    }

    public void Delete(TEntity entity)
    {
        _entities.Remove(entity);
    }
}
941 chars
46 lines

In this example, the IRepository interface specifies the CRUD operations that can be performed on a particular domain entity, while the Repository class implements these operations using Entity Framework to interact with the database.

To use the repository class, you would first need to create a DbContext instance for your database and then create a new instance of the repository by passing the DbContext object as a parameter:

main.cs
var dbContext = new MyDbContext();
var userRepository = new Repository<User>(dbContext);

var user = userRepository.Get(1);
user.Name = "John Smith";
userRepository.Update(user);
dbContext.SaveChanges();
204 chars
8 lines

This code retrieves a user from the database using the Get method, updates it, and then saves the changes to the database using the DbContext's SaveChanges method.

gistlibby LogSnag