Skip to content

Instantly share code, notes, and snippets.

@mariobot
Created August 10, 2015 18:52
Show Gist options
  • Save mariobot/0dd5d4ff9d7d8b1b4f1a to your computer and use it in GitHub Desktop.
Save mariobot/0dd5d4ff9d7d8b1b4f1a to your computer and use it in GitHub Desktop.
Generic Repository Complete
namespace CodedHomes.Data
{
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 argument of context its necesary.");
this.Context = context;
this.DBSet = this.Context.Set<T>();
}
public IQueryable<T> GetAll() {
return this.DBSet;
}
public T GetById(int id){
return this.DBSet.Find(id);
}
public void Add(T entity) {
DbEntityEntry entry = this.Context.Entry(entity);
if (entry.State != EntityState.Detached)
entry.State = EntityState.Added;
this.DBSet.Add(entity);
}
public void Update(T entity)
{
DbEntityEntry entry = this.Context.Entry(entity);
if (entry.State == EntityState.Detached)
this.DBSet.Attach(entity);
entry.State = EntityState.Modified;
}
public 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 void Delete(int id)
{
var entity = this.GetById(id);
if (entity != null)
this.Delete(entity);
}
public void Detach(T entity)
{
DbEntityEntry entry = this.Context.Entry(entity);
entry.State = EntityState.Detached;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment