Skip to content

Instantly share code, notes, and snippets.

@jpolvora
Created November 8, 2011 21:27
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/1349307 to your computer and use it in GitHub Desktop.
Save jpolvora/1349307 to your computer and use it in GitHub Desktop.
using System;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.Objects;
using System.Linq;
namespace Metavision.Infra.Data
{
/// <summary>
/// Implementação de UnitOfWork para EntityFramework (CodeFirst)
/// Basicamente funciona abstraindo as operações do DbContext
/// Permitindo trabalhar com injeção de dependência
/// </summary>
public class CodeFirstUnitOfWork : UnitOfWorkBase, IUnitOfWork, IObjectContextAdapter
{
#region Members
private readonly DbContext _dbContext;
#endregion
#region Ctor
public CodeFirstUnitOfWork(DbContext dbContext = null)
{
_dbContext = dbContext ?? Container.GetService<DbContext>(false);
}
#endregion
#region Implementation of IObjectContextAdapter
public ObjectContext ObjectContext
{
get { return ((IObjectContextAdapter)_dbContext).ObjectContext; }
}
#endregion
#region Implementation of IUnitOfWork
public T Find<T>(params object[] keyValues) where T : class, new()
{
return GetDbSet<T>().Find(keyValues);
}
public void Add<T>(T entity) where T : class
{
GetDbSet<T>().Add(entity);
}
public void Remove<T>(T entity) where T : class
{
GetDbSet<T>().Remove(entity);
}
public IQueryable<T> Get<T>() where T : class
{
return GetDbSet<T>();
}
private DbSet<T> GetDbSet<T>() where T : class
{
DbSet<T> set;
if (Sets.ContainsKey(typeof(T)))
set = (DbSet<T>)Sets[typeof(T)];
else
{
set = _dbContext.Set<T>();
Sets[typeof(T)] = set;
}
return set;
}
internal override void StartTransaction()
{
if (!InTransaction)
{
ObjectContext.Connection.Close();
if (ObjectContext.Connection.State != ConnectionState.Open)
{
ObjectContext.Connection.Open();
CurrentTransaction = ObjectContext.Connection.BeginTransaction();
}
}
}
public int Commit()
{
var hasChanges = StackRepositories.Any(w => w.HasChanges);
if (!hasChanges) return 0;
try
{
StartTransaction();
var errors = _dbContext.GetValidationErrors();
var errorsCount = errors.Count();
if (errorsCount > 0)
{
RollBack();
return errorsCount * -1;
}
var count = _dbContext.SaveChanges();
CurrentTransaction.Commit();
SetHasChangesToFalse();
return count;
}
catch (Exception)
{
RollBack();
return -1;
}
}
public void RollBack()
{
SetHasChangesToFalse();
if (!InTransaction) return;
foreach (var dbEntityEntry in _dbContext.ChangeTracker.Entries())
{
if (dbEntityEntry.State != EntityState.Added)
dbEntityEntry.Reload();
}
CurrentTransaction.Rollback();
}
#endregion
public override void Dispose()
{
base.Dispose();
_dbContext.Dispose();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment