Skip to content

Instantly share code, notes, and snippets.

@oclockvn
Created June 12, 2015 15:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oclockvn/cd8560db7749811bb8ca to your computer and use it in GitHub Desktop.
Save oclockvn/cd8560db7749811bb8ca to your computer and use it in GitHub Desktop.
public class GenericRepository<T> : IGenericRepository<T> where T : class
{
protected ApplicationDbContext _db { get; set; }
protected DbSet<T> _table = null;
public GenericRepository()
{
_db = new ApplicationDbContext();
_table = _db.Set<T>();
}
public GenericRepository(ApplicationDbContext db)
{
_db = db;
_table = _db.Set<T>();
}
public IEnumerable<T> SelectAll()
{
//return _table.AsNoTracking().ToList();
return _table.ToList();
}
public T SelectById(object id)
{
try
{
return _table.Find(id);
}
catch
{
return null;
}
}
public void Insert(T obj)
{
_table.Add(obj);
}
public void Update(T obj)
{
_table.Attach(obj);
_db.Entry(obj).State = EntityState.Modified;
}
public void Delete(object id)
{
T existing = _table.Find(id);
_table.Remove(existing);
}
public void Save()
{
_db.SaveChanges();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment