Repository Pattern pros and cons of each implementation

Viewed 6770

Hi looking at the repository pattern which commonly seems to be implemented something like:

public class GenericRepository<TEntity> where TEntity : class
{
    // other business

    public virtual TEntity GetByID(object id)
    {
        return db.Set().Find(id);
    }

    public virtual void Insert(TEntity entity)
    {
        db.Set().Add(entity);
    }

    public virtual void Delete(object id)
    {
        TEntity entityToDelete = db.Set().Find(id);
        Delete(entityToDelete);
    }

    public virtual void Update(TEntity entityToUpdate)
    {
        db.Set().Attach(entityToUpdate);
        context.Entry(entityToUpdate).State = EntityState.Modified;
    }
}

So for every type you want to work with (ie update) you need to instantiate a repository.

So if I had two types I wanted to save Cars and Trucks I would need to go:

var carRepository = new GernericRepository<Car>();
carRepository.Update(myCar);

var truckRepository = new GernericRepository<Truck>();
carRepository.Update(myTruck);

So then you have seperate repositories for each type. To make sure you save everything at once you need the unitOfWork to ensure they all use the same context and save at one time.

Surely wouldn't it be better to have something like:

public class GenericRepository
{
    // other business

    public virtual TEntity GetByID<TEntity>(object id) where TEntity : class
    {
        return db.Set<TEntity>().Find(id);
    }

    public virtual void Insert<TEntity>(TEntity entity) where TEntity : class
    {
        db.Set<TEntity>().Add(entity);
    }

    public virtual void Delete<TEntity>(object id) where TEntity : class
    {
        TEntity entityToDelete = db.Set<TEntity>().Find(id);
        Delete(entityToDelete);
    }

    public virtual void Update<TEntity>(TEntity entityToUpdate) where TEntity : class
    {
        db.Set<TEntity>().Attach(entityToUpdate);
        context.Entry(entityToUpdate).State = EntityState.Modified;
    }
}

This means the repository only needs to be instantiated once and therefore is truely generic?

So you could update your cars and trucks like this:

var repository = new GernericRepository<Car>();
repository.Update<Car>(myCar);
rRepository.Update<Truck>(myTruck);

Surely this is a better method? Am I missing something? It automatically has only one context too.

2 Answers
Related