Instantly share code, notes, and snippets.

Embed
What would you like to do?
public interface IUnitOfWork : IDisposable
{
#region UoW
Database Database { get; }
DbChangeTracker ChangeTracker { get; }
DbContextTransaction Transaction { get; }
DbContextConfiguration Configuration { get; }
DbSet Set(Type entityType);
DbSet<T> Set<T>() where T : class;
int SaveChanges();
void Commit();
DbContextTransaction StartTransaction();
DbContextTransaction StartTransaction(IsolationLevel isolationLevel);
void Rollback();
void Save();
DbEntityEntry Entry(object targetValue);
#endregion
DbSet<Entidade> VariosDbSets { get; }
void SaveAndCommit();
void SaveAndCommitAndStartTransaction();
}
public sealed class MeuContext : DbContext, IUnitOfWork
{
public DbSet<AplicacaoParceira> AplicacoesParceiras { get; set; }
public DbContextTransaction Transaction { get; private set; }
public void Commit()
{
if (Transaction == null || _rolledback) return;
Transaction.Commit();
Transaction.Dispose();
Transaction = null;
}
public DbContextTransaction StartTransaction()
=> Transaction ?? (Transaction = Database.BeginTransaction());
public DbContextTransaction StartTransaction(IsolationLevel isolationLevel)
=> Transaction ?? (Transaction = Database.BeginTransaction(isolationLevel));
public void Rollback()
{
if (Transaction?.UnderlyingTransaction.Connection == null || _rolledback) return;
Transaction.Rollback();
_rolledback = true;
}
public void Save()
{
try
{
ChangeTracker.DetectChanges();
SaveChanges();
}
catch (DbEntityValidationException exception)
{
Rollback();
throw new EntidadeInvalidaException(string.Join(Environment.NewLine, exception.EntityValidationErrors.SelectMany(e => e.ValidationErrors).Select(e => $"{e.PropertyName} => {e.ErrorMessage}")));
}
catch
{
Rollback();
throw;
}
}
public void SaveAndCommit()
{
try
{
Save();
#if !NCRUNCH
Commit();
#endif
}
catch
{
//Dispose não deve lançar exceção
}
}
public void SaveAndCommitAndStartTransaction()
{
SaveAndCommit();
StartTransaction();
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Configurations.AddFromAssembly(CurrentAssembly);
modelBuilder.Properties<string>()
.Configure(c => c.HasColumnType("varchar").HasMaxLength(255).IsRequired());
base.OnModelCreating(modelBuilder);
}
protected override void Dispose(bool disposing)
{
if (_rolledback)
Rollback();
else if (Transaction != null && !_rolledback)
SaveAndCommit();
base.Dispose(disposing);
}
}
public class Repository<T> : IRepository<T> where T : Entidade
{
protected IUnitOfWork Context { get; }
public Repository(IUnitOfWork unitOfWork)
=> Context = unitOfWork;
//Metodos do repository
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment