I am trying to implement UOW with Generic Repository pattern. Here is how my src looks like
public interface IRepository<T>
: IDisposable where T : class
{
void Add(T entity);
void Delete(T entity);
void Save();
void Update(T entity);
IQueryable<T> GetQuery();
IEnumerable<T> GetAll();
IEnumerable<T> Find(Expression<Func<T, bool>> predicate);
T Single(Expression<Func<T, bool>> predicate);
}
public interface IUnitOfWork
{
void InitTransaction();
void Rollback();
void CommitTransaction();
}
public class EntityRepository<C, T> : BaseRepository<C, T>, IUnitOfWork
where C : CustomerContext
where T : class
{
protected DbSet<T> DataSet
{
get
{
return _ctx.Set<T>();
}
}
public EntityRepository(C ctx)
: base(ctx)
{
}
public override IQueryable<T> GetQuery()
{
return DataSet;
}
public override void Add(T entity)
{
DataSet.Add(entity);
}
public override void Save()
{
_ctx.SaveChanges();
}
public override void Delete(T entity)
{
DataSet.Remove(entity);
}
public override IEnumerable<T> GetAll()
{
return DataSet.ToList<T>();
}
public override IEnumerable<T> Find(Expression<Func<T, bool>> predicate)
{
return GetQuery().Where(predicate).ToList<T>();
}
public override T Single(Expression<Func<T, bool>> predicate)
{
return GetQuery().Where(predicate).SingleOrDefault();
}
public override void Update(T entity)
{
_ctx.Entry<T>(entity).State = System.Data.Entity.EntityState.Modified;
}
public void InitTransaction()
{
throw new NotImplementedException();
}
public void Rollback()
{
throw new NotImplementedException();
}
public void CommitTransaction()
{
throw new NotImplementedException();
}
}}
This is where I have implemented IUnitOfWork in DbContext class.
public class CustomerContext :
DbContext, IUnitOfWork
{
private DbContextTransaction _dbTransaction;
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
}
public void InitTransaction()
{
_dbTransaction = this.Database.BeginTransaction();
}
public void Rollback()
{
_dbTransaction.Rollback();
}
public void CommitTransaction()
{
_dbTransaction.Commit();
}
#region DbSet
public DbSet<User> Users{ get; set; }
public DbSet<Contact> Contacts {get; set;}
#endregion DbSet
}
EF Relation
One to many -> One user can have multiple contacts
Referred to number of articles but not sure how do I put the User & Contact CRUD in one transaction.
public class CustomerController : APIController
{
}
Aucun commentaire:
Enregistrer un commentaire