Skip to content

Instantly share code, notes, and snippets.

@jpolvora
Last active August 29, 2015 14:08
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 jpolvora/43abbf3cad4d4ca1bb7b to your computer and use it in GitHub Desktop.
Save jpolvora/43abbf3cad4d4ca1bb7b to your computer and use it in GitHub Desktop.
simple repository base based on EF
public class DbContextUnitOfWork //: IUnitOfWork
{
public System.Data.Entity.DbContext Context { get; private set; }
private bool _disposed;
public DbContextUnitOfWork(System.Data.Entity.DbContext context)
{
Context = context;
}
public bool Commit()
{
if (_disposed)
throw new InvalidOperationException("UnitOfWork was disposed! Please start a new unit of work operation");
return Context.SaveChanges() >= 0;
}
public void Dispose()
{
_disposed = true;
}
}
public class RepositoryBase<TEntity> where TEntity : class, new()
{
private readonly DbContext _context;
private readonly IDbSet<TEntity> _set;
public RepositoryBase(DbContextUnitOfWork uow)
{
_context = uow.Context;
_set = _context.Set<TEntity>();
}
public TEntity Find(object key)
{
return _set.Find(key);
}
public IEnumerable<TEntity> Query(Func<TEntity, bool> predicate)
{
return _set.Where(predicate);
}
public IQueryable<TEntity> AsQueryable()
{
return _set;
}
public void Add(TEntity instance)
{
_context.Entry(instance).State = EntityState.Added;
}
public void Edit(TEntity instance)
{
_context.Entry(instance).State = EntityState.Modified;
}
public void Remove(TEntity instance)
{
_context.Entry(instance).State = EntityState.Deleted;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment