Skip to content

Instantly share code, notes, and snippets.

@jpolvora
Last active Aug 29, 2015
Embed
What would you like to do?
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