lisansi同学回复(项目架构开发:数据访问层之UnitOfWork)要求,补上Dapper的DbContext实现

 using Dapper.Contrib.Extensions;
using HG.Infrastructure.Common;
using System;
using System.Collections.Generic;
using System.Data;
using System.Transactions; namespace HG.Data.Dapper
{
public class DbContext
{
public IDbConnection Conn { get; set; } private Dictionary<object, Action> addEntities;
private Dictionary<object, Action> updateEntities;
private Dictionary<object, Action> deleteEntities; public DbContext()
{
Conn = DbConnectionFactory.CreateConnection(Enums.Core); addEntities = new Dictionary<object, Action>();
updateEntities = new Dictionary<object, Action>();
deleteEntities = new Dictionary<object, Action>();
} public void Add<TEntity>(TEntity entity) where TEntity : class
{
this.addEntities.Add(entity, () =>
{
Conn.Insert<TEntity>(entity);
});
} public void Update<TEntity>(TEntity entity) where TEntity : class
{
this.updateEntities.Add(entity, () =>
{
Conn.Update(entity);
});
} public void Delete<TEntity>(TEntity entity) where TEntity : class
{
this.deleteEntities.Add(entity, () =>
{
Conn.Delete(entity);
});
} public TEntity Get<TEntity>(int id) where TEntity : class
{
return Conn.Get<TEntity>(id);
} public int SaveChanges()
{
int count = ;
using (TransactionScope scope = new TransactionScope())
{
foreach (var entity in deleteEntities.Keys)
{
this.deleteEntities[entity]();
} foreach (var entity in updateEntities.Keys)
{
this.updateEntities[entity]();
} foreach (var entity in addEntities.Keys)
{
this.addEntities[entity]();
} scope.Complete(); count = deleteEntities.Count + updateEntities.Count + addEntities.Count; deleteEntities.Clear();
updateEntities.Clear();
addEntities.Clear(); if (Conn != null)
{
if (Conn.State == ConnectionState.Open)
{
Conn.Close();
} // Conn.Dispose();
}
} return count;
}
}
}
UnitOfWork相应改成如下
 using HG.Data.Interface;
using System;
using System.Data; namespace HG.Data.Dapper
{
public class UnitOfWork : DbContext, IUnitOfWork, ICRUDUnitOfWork
{
public void RegisterNew<TEntity>(TEntity entity)
where TEntity : class
{
base.Add<TEntity>(entity);
} public void RegisterDirty<TEntity>(TEntity entity)
where TEntity : class
{
base.Update<TEntity>(entity);
} public void RegisterDeleted<TEntity>(TEntity entity)
where TEntity : class
{
base.Delete<TEntity>(entity);
} public void RegisterClean<TEntity>(TEntity entity)
where TEntity : class
{ } //public TEntity Get<TEntity>(int id)
// where TEntity : class
//{
// return base.Get<TEntity>(id);
//} public bool Commit()
{
return base.SaveChanges() > ;
} public void Rollback()
{
throw new NotImplementedException();
}
}
}
05-07 12:01