Skip to content

Instantly share code, notes, and snippets.

@robsonfaxas
Created October 23, 2018 20:58
Show Gist options
  • Save robsonfaxas/ea25135e9cf82a7df77b0e14bc59b20b to your computer and use it in GitHub Desktop.
Save robsonfaxas/ea25135e9cf82a7df77b0e14bc59b20b to your computer and use it in GitHub Desktop.
TransactionScope #transaction
-- Interface
public interface IContextTransactionScope
{
void ExecuteInTransactionScope(Action action);
TResult ExecuteInTransactionScope<TResult>(Func<TResult> predicate);
DbContext GetContext();
}
-- Implementação em Entity
public class ContextTransactionScope : IContextTransactionScope
{
private DbContext _context;
public ContextTransactionScope(DbContext context)
{
_context = context;
}
public void ExecuteInTransactionScope(Action action)
{
using (var transaction = _context.Database.BeginTransaction())
{
try
{
action();
transaction.Commit();
}
catch (DbEntityValidationException dbEntityValidationException)
{
transaction.Rollback();
throw;
}
catch (Exception)
{
transaction.Rollback();
throw;
}
}
}
public TResult ExecuteInTransactionScope<TResult>(Func<TResult> predicate)
{
using (var transaction = _context.Database.BeginTransaction())
{
try
{
var result = predicate();
transaction.Commit();
return result;
}
catch (Exception)
{
transaction.Rollback();
throw;
}
}
}
public DbContext GetContext()
{
throw new NotImplementedException();
}
public void Dispose()
{
// OBS: não pode dar Dispose no _context pois ele é injetado!!!
//if (_context != null)
//{
// _context.Dispose();
// _context = null;
//}
//GC.SuppressFinalize(this);
}
}
-- Generic Repository
public abstract class GenericRepository<TEntity, TDbContext> : IGenericRepository<TEntity>
where TEntity : class, ICloneable
where TDbContext : DbContext
{
protected TDbContext _context;
protected GenericRepository(TDbContext context)
{
_context = context;
}
public TEntity Get(Expression<Func<TEntity, bool>> predicate)
{
return _context.Set<TEntity>().AsNoTracking().FirstOrDefault(predicate);
}
public TEntity Get(Expression<Func<TEntity, bool>> predicate, params Expression<Func<TEntity, object>>[] includeProperties)
{
var query = _context.Set<TEntity>().AsNoTracking().AsQueryable();
foreach (var includeProperty in includeProperties)
{
query = query.Include(includeProperty);
}
return query.FirstOrDefault(predicate);
}
public virtual TEntity Add(TEntity entity)
{
var clonedEntity = (TEntity)entity.Clone();
_context.Entry(clonedEntity).State = EntityState.Added;
_context.SaveChanges();
_context.Entry(clonedEntity).State = EntityState.Detached; // remove a referência do contexto para evitar problemas.
return clonedEntity;
}
public virtual TEntity Update(TEntity entity)
{
var clonedEntity = (TEntity) entity.Clone();
_context.Entry(clonedEntity).State = EntityState.Modified;
_context.SaveChanges();
_context.Entry(clonedEntity).State = EntityState.Detached; // remove a referência do contexto para evitar problemas.
return clonedEntity;
}
public void Delete(TEntity entity)
{
_context.Set<TEntity>().Remove(entity);
_context.SaveChanges();
}
public IQueryable<TEntity> GetAll()
{
return _context.Set<TEntity>().AsNoTracking().AsQueryable();
}
public IQueryable<TEntity> GetAll(Expression<Func<TEntity, bool>> predicate)
{
return _context.Set<TEntity>().Where(predicate).AsNoTracking().AsQueryable();
}
public IQueryable<TEntity> GetAll(Expression<Func<TEntity, bool>> predicate,
params Expression<Func<TEntity, object>>[] includeProperties)
{
var query = _context.Set<TEntity>().AsQueryable();
foreach (var includeProperty in includeProperties)
{
query = query.Include(includeProperty);
}
return query.AsNoTracking().Where(predicate);
}
public int Count()
{
return _context.Set<TEntity>().Count();
}
public int Count(Expression<Func<TEntity, bool>> predicate)
{
return _context.Set<TEntity>().Where(predicate).Count();
}
}
// Service implementada
public class ElderlyService : ServiceBase, IElderlyService
{
private readonly IElderlyRepository _elderlieRepository;
public ElderlyService(ElderlyRepository elderlyRepository)
{
_elderlieRepository = elderlyRepository;
}
public void Update(Elderly elderly)
{
_elderlieRepository.Update(elderly);
}
public Elderly Get(User user)
{
return _elderlieRepository.Get(x => x.UserId == user.UserId && x.Status.Equals(GenericStatus.Active));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment