Skip to content

Instantly share code, notes, and snippets.

@JulienSansot
Created December 4, 2013 06:11
Show Gist options
  • Save JulienSansot/7783122 to your computer and use it in GitHub Desktop.
Save JulienSansot/7783122 to your computer and use it in GitHub Desktop.
Entity Framework Generic Repository
public interface IRepository
{
IQueryable<T> Query<T>() where T : class;
T Add<T>(T entity) where T : class;
T Update<T>(T entity) where T : class;
void Delete<T>(T entity) where T : class;
}
public class Repository : IRepository
{
private readonly DbContext _context;
public Repository(DbContext context)
{
_context = context;
}
public IQueryable<T> Query<T>() where T : class
{
return _context.Set<T>().AsQueryable().AsNoTracking();
}
public T Add<T>(T entity) where T : class
{
_context.Entry(entity).State = System.Data.EntityState.Added;
Save();
return entity;
}
public T Update<T>(T entity) where T : class
{
_context.Entry(entity).State = System.Data.EntityState.Modified;
Save();
return entity;
}
public void Delete<T>(T entity) where T : class
{
_context.Entry(entity).State = System.Data.EntityState.Deleted;
Save();
}
private void Save()
{
_context.SaveChanges();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment