Generic Repository For Web Apps I was developing a web app using Entity Framework 6 and MVC 5. For the data access layer, I eased the job and wrote a generic repository as following:

public class GenericRepository&lt;T&gt; where T : class
{
    private EFDbContext context = new EFDbContext();


    public IEnumerable&lt;T&gt; GetAll()
    {
        return context.Set&lt;T&gt;();
    }
    public T GetByID(object id)
    {
        return context.Set&lt;T&gt;().Find(id);
    }
    public void Insert(T entity)
    {
        context.Set&lt;T&gt;().Add(entity);
        context.SaveChanges();
    }
    public void Update(T entity)
    {
        context.Entry(entity).State = System.Data.Entity.EntityState.Modified;
        context.SaveChanges();
    }
    public T Delete(T entity)
    {
        if (entity != null)
            context.Entry(entity).State = System.Data.Entity.EntityState.Deleted;
        context.SaveChanges();
        return entity;
    }
}


In controllers, I declare it as a global variable and use it in different action methods.

There is one big problem with this approach:

Flexibility: I'm not able to do anything specific with this repository, like preserving some fields, etc. I'm forced to use some hacks to achieve things like that.

I know that many believe using a repository pattern with context is not useful. The main reason that I tried that was to make my controllers cleaner and a generic one to save time. But I guess it doesn't worse it. I think next time I'll just use the EF context without any additional pattern.

What do you suggest, using this library, using this with Unit of Work, or something else? Is there any other problem with this code?
One major drawback...

public void Insert(T entity)
{
    context.Set&lt;T&gt;().Add(entity);
    context.SaveChanges();
}


...is that you've just destroyed the usefulness of a unit of work. DbContext wraps a database transaction, and what's great about transactions, is that they allow you to commit a "set" of changes all at once.

But you're calling SaveChanges every time anything happens to any entity, which means if you have 1 request doing 20 calls into that repository, you're effectively committing 20 transactions.

A new unit of work instance should be created, and die with each request: SaveChanges should be called, ideally, exactly once in the lifetime of the DbContext.