Skip to content

Instantly share code, notes, and snippets.

@ssajous
Last active December 19, 2015 22:48
Show Gist options
  • Save ssajous/6029621 to your computer and use it in GitHub Desktop.
Save ssajous/6029621 to your computer and use it in GitHub Desktop.
Entity Framework generic repository. Meant to be used as a wrapper to access a particular type/table from DbContext
public class GenericRepository<T> : IRepository<T> where T : class
{
protected DbSet<T> DBSet {get;set;}
protected DbContext Context { get; set; }
public GenericRepository(DbContext context)
{
if (context == null)
{
throw new ArgumentException("An instance of DbContext is " +
"required to use this repository.", "context");
}
this.Context = context;
this.DBSet = this.Context.Set<T>();
}
public virtual IQueryable<T> GetAll()
{
return this.DBSet;
}
public virtual T GetById(int id)
{
return this.DBSet.Find(id);
}
public virtual void Add(T entity)
{
DbEntityEntry entry = this.Context.Entry(entity);
if (entry.State != EntityState.Detached)
{
entry.State = EntityState.Added;
}
else
{
this.DBSet.Add(entity);
}
}
public virtual void Update(T entity)
{
DbEntityEntry entry = this.Context.Entry(entity);
if (entry.State == EntityState.Detached)
{
this.DBSet.Attach(entity);
}
entry.State = EntityState.Modified;
}
public virtual void Detach(T entity)
{
DbEntityEntry entry = this.Context.Entry(entity);
entry.State = EntityState.Detached;
}
public virtual void Delete(T entity)
{
DbEntityEntry entry = this.Context.Entry(entity);
if (entry.State != EntityState.Deleted)
{
entry.State = EntityState.Deleted;
}
else
{
this.DBSet.Attach(entity);
this.DBSet.Remove(entity);
}
}
public virtual void Delete(int id)
{
var entity = this.GetById(id);
if (entity != null)
{
this.Delete(entity);
}
}
}
public interface IRepository<T> where T : class
{
IQueryable<T> GetAll();
T GetById(int id);
void Add(T entity);
void Update(T entity);
void Delete(T entity);
void Delete(int id);
void Detach(T entity);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment