Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Repository Pattern 2014 + UnitOfWork
public interface IRepository<T> where T : class, new()
{
T Find(object key);
IEnumerable<T> Query(Func<T, bool> predicate);
IQueryable<T> AsQueryable();
void Add(T instance);
void Edit(T instance);
void Remove(T instance);
}
public interface IUnitOfWork: IDisposable
{
bool Commit();
}
/*implementações*/
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 DbContextRepository<TEntity> : IRepository<TEntity> where TEntity : class, new()
{
private readonly DbContext _context;
private readonly IDbSet<TEntity> _set;
public DbContextRepository(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;
}
}
/* teste real */
public class Arquivo
{
[Key]
public int Id { get; set; }
[StringLength(255)]
public string Nome { get; set; }
[ForeignKey("PastaId")]
public Pasta Pasta { get; set; }
public int PastaId { get; set; }
}
public class Pasta
{
[Key]
public int Id { get; set; }
[StringLength(255)]
public string Nome { get; set; }
}
/* DbContext com as duas entidades mencionadas acima */
public class TestContext : DbContext
{
public DbSet<Arquivo> Arquivos { get; set; }
public DbSet<Pasta> Pastas { get; set; }
}
/* especialização não é obrigatória, mas facilita a construção */
public class TestUnitOfWork : DbContextUnitOfWork
{
public TestUnitOfWork()
: base(new TestContext())
{
}
}
/* especialização não é obrigatória, mas facilita a construção */
public class TestRepositoryBase<TEntity> : DbContextRepository<TEntity> where TEntity : class, new()
{
public TestRepositoryBase(TestUnitOfWork uow)
: base(uow)
{
}
}
/* teste */
using (var unitOfWork = new TestUnitOfWork())
{
/*PASTA*/
//cria o repositório passando a instância de unitOfWork
var repoPastas = new TestRepositoryBase<Pasta>(unitOfWork);
var pastaRaiz = repoPastas.Query(x => x.Nome.Equals("/")).FirstOrDefault();
if (pastaRaiz == null)
{
//cria a pasta raiz
pastaRaiz = new Pasta() { Nome = "/" };
repoPastas.Add(pastaRaiz);
}
/*ARQUIVO*/
//cria o repositório passando a instância de unitOfWork
var repoArquivos = new TestRepositoryBase<Arquivo>(unitOfWork);
var arquivos = repoArquivos.Query(x => x.Nome.Contains("readme.txt"));
if (!arquivos.Any())
{
var arquivo = new Arquivo()
{
Nome = "readme.txt",
Pasta = pastaRaiz
};
repoArquivos.Add(arquivo);
}
//salva tudo
unitOfWork.Commit();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment