Last active
August 29, 2015 14:08
-
-
Save jpolvora/43abbf3cad4d4ca1bb7b to your computer and use it in GitHub Desktop.
simple repository base based on EF
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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