.NET Core 工作单元unitofwork 实现,基于NPOCO
现有项目中的orm 并非efcore,而是非主流的npoco,本身没有自带工作单元所以需要自己手撸一个,现记录一下,基于其他orm的工作单元照例实现应该没有什么问题
该实现基于NPOCO,针对其他的ORM实现,所有的实现都基于接口,如需转成其他ORM,只需要将部分实现类重写即可,如UnitOfWorkImpl
实体基类,所有实体继承该类
namespace test.Core
{
/// <summary>
/// 实体基类
/// </summary>
public class EntityBase
{
/// <summary>
/// 唯一标识
/// </summary>
public long Id { get; set; } public EntityBase()
{
// Id = GeneratePrimaryKeyIdHelper.GetPrimaryKeyId();
}
}
}
自定义的事务接口实现类
using test.Core;
using NPoco;
using System.Data; namespace test.DAL
{
internal class DBTransactionImpl : IDBTransaction
{
IDatabase db; public DBTransaction(IDatabase db)
{
this.db = db;
this.db.BeginTransaction();
} public virtual void Complete()
{
db.CompleteTransaction();
db = null;
} public void Dispose()
{
if (db != null)
{
db.AbortTransaction();
}
} }
}
事务接口
using System; namespace test.Core
{
public interface IDBTransaction : IDisposable
{
void Complete();
}
}
仓储接口:命令类(提交数据的接口,不包含查询的服务)
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using test.Core; namespace test.IDAL
{
public interface ICommandBaseRepository
{
#region 新增
/// <summary>
/// 插入实体
/// </summary>
Task<object> InsertAsync<T>(T entity) where T : EntityBase; /// <summary>
/// 批量插入实体
/// </summary>
Task<bool> InsertBatchAsync<T>(IList<T> entities) where T : EntityBase;
#endregion #region 更新
/// <summary>
/// 更新单个实体
/// </summary>
Task<bool> UpdateAsync<T>(T entity) where T : EntityBase; /// <summary>
/// 根据实体更新部分字段
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="entity"></param>
/// <param name="fields"></param>
/// <returns></returns>
Task<bool> UpdateAsync<T>(T entity, Expression<Func<T, object>> fields) where T : EntityBase; /// <summary>
/// 更新实体的部分字段
/// </summary>
/// <param name="entity"></param>
/// <param name="columns"></param>
/// <returns></returns>
Task<bool> UpdateAsync<T>(T entity, IList<string> columns) where T : EntityBase; /// <summary>
/// 更新多个实体
/// </summary>
/// <param name="entities"></param>
/// <returns></returns>
Task<bool> UpdateBatchAsync<T>(IList<T> entities) where T : EntityBase; /// <summary>
/// 根据id集合更新多个记录的某个字段
/// </summary>
/// <typeparam name="TPrimaryKeyType">主键值类型 long,int等</typeparam>
/// <typeparam name="TColunmValue">字段值类型 long,int等</typeparam>
/// <param name="idList">id集合</param>
/// <param name="column">字段数据,key字段名,value字段值</param>
/// <returns></returns>
Task<bool> UpdateSingleFieldByIdsAsync<TPrimaryKeyType, TColunmValue>(IList<TPrimaryKeyType> idList, KeyValuePair<string, TColunmValue> column); /// <summary>
/// 保存实体,有则更新,无则新增
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
Task<bool> SaveAsync<T>(T entity) where T : EntityBase; #endregion #region 删除 /// <summary>
/// 逻辑删除
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
Task<bool> SoftDeleteAsync<TPrimaryKeyType>(TPrimaryKeyType id); /// <summary>
/// 逻辑删除
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
Task<bool> SoftDeleteBatchAsync<TPrimaryKeyType>(IList<TPrimaryKeyType> id); /// <summary>
/// 删除记录
/// </summary>
// Task<bool> DeleteAsync<TPrimaryKeyType>(TPrimaryKeyType id); /// <summary>
/// 批量删除记录
/// </summary>
// Task<bool> DeleteBatchAsync<TPrimaryKeyType>(IList<TPrimaryKeyType> idList); #endregion #region 事务模块
/// <summary>
/// 开始事务(返回事务对象)
/// </summary>
/// <returns></returns>
IDBTransaction BeginDBTransaction(); /// <summary>
/// 开启事务(不返回事务对象)
/// </summary>
/// <returns></returns>
void BeginNewDBTransaction(); /// <summary>
/// 提交事务事务
/// </summary>
void CompleteDBTransaction(); /// <summary>
/// 中断结束事务
/// </summary>
void AbortDBTransaction(); #endregion
}
}
仓储接口:查询仓储服务
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks; namespace test.IDAL
{
public interface IQueryBaseRepository
{
/// <summary>
/// 获得单条数据
/// </summary>
/// <typeparam name="TPrimaryKeyType"></typeparam>
/// <param name="id"></param>
/// <returns></returns>
Task<T> GetAsync<T, TPrimaryKeyType>(TPrimaryKeyType id); /// <summary>
/// 根据id集合获取多条数据
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="TPrimaryKeyType"></typeparam>
/// <param name="ids"></param>
/// <returns></returns>
Task<List<T>> GetListByIdsAsync<T, TPrimaryKeyType>(List<TPrimaryKeyType> ids); /// <summary>
/// 根据某个唯一字段列获取单条数据(唯一值)
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="TColunmValue"></typeparam>
/// <param name="column"></param>
/// <returns></returns>
Task<T> GetSingleAsync<T, TColunmValue>(KeyValuePair<string, TColunmValue> column); /// <summary>
/// 根据主键是否存在记录
/// </summary>
Task<bool> ExistsAsync<TPrimaryKeyType>(TPrimaryKeyType id); /// <summary>
/// 某个字段是否唯一
/// </summary>
/// <typeparam name="TColunmValue"></typeparam>
/// <param name="column"></param>
/// <returns>true 唯一 false 不唯一</returns>
Task<bool> IsUniqueAsync<TColunmValue>(KeyValuePair<string, TColunmValue> column); }
}
工作单元接口
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using test.Core; namespace test.IDAL
{
public interface IUnitOfWork
{
/// <summary>
/// 插入
/// </summary>
/// <param name="entity"></param>
/// <param name="unitofWorkRepository"></param>
void RegisterInsert(EntityBase entity, ICommandBaseRepository unitofWorkRepository); /// <summary>
/// 保存,不支持多个同一类实体(同一个类型实体只能添加一个,否则会异常)
/// </summary>
/// <param name="entity"></param>
/// <param name="unitofWorkRepository"></param>
void RegisterSave(EntityBase entity, ICommandBaseRepository unitofWorkRepository); /// <summary>
/// 更新
/// </summary>
/// <param name="entity"></param>
/// <param name="unitofWorkRepository"></param>
void RegisterUpdate(EntityBase entity, ICommandBaseRepository unitofWorkRepository); /// <summary>
/// 删除
/// </summary>
/// <param name="id"></param>
/// <param name="unitofWorkRepository"></param>
void RegisterDelete(object id, ICommandBaseRepository unitofWorkRepository); /// <summary>
/// 根据字段更新
/// </summary>
/// <param name="entity"></param>
/// <param name="fields"></param>
/// <param name="unitofWorkRepository"></param>
void RegisterUpdateByFields(EntityBase entity, IList<string> fields, ICommandBaseRepository unitofWorkRepository); /// <summary>
/// 根据id集合更新单个字段
/// </summary>
/// <param name="id"></param>
/// <param name="column"></param>
/// <param name="unitofWorkRepository"></param>
void RegisterUpdateSingleFieldByIds(IList<object> id, KeyValuePair<string, object> column, ICommandBaseRepository unitofWorkRepository); Task CommitAsync();
}
}
自定义的获取db对象接口,保证一个请求内db是同一个对象即可,可通过依赖注入的addscoped实现
using test.DAL.Repositories;
using System;
using System.Collections.Generic;
using System.Text; namespace test.DAL
{
internal interface IScopeDBFactory
{
CustomDatabase GetScopeDb();
}
}
IScopeDBFactory 实现类,自行实现即可
using MySql.Data.MySqlClient;
using test.Core;
using NPoco;
using NPoco.FluentMappings;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Reflection;
using System.Text; namespace test.DAL.Repositories
{
internal class ScopeDBFactoryImpl : IScopeDBFactory
{ protected CustomDatabase Db;
public CustomDatabase GetScopeDb()
{
} }
}
unitofwork 接口实现
using test.Core;
using test.DAL;
using test.DAL.Repositories;
using test.IDAL;
using NPoco;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Transactions; namespace test.DAL
{
internal class UnitOfWorkImpl : IUnitOfWork
{ private Dictionary<ICommandBaseRepository, List<EntityBase>> addedEntities;
private Dictionary<ICommandBaseRepository, List<EntityBase>> changedEntities;
private Dictionary<ICommandBaseRepository, List<object>> deletedEntities;
private Dictionary<ICommandBaseRepository, EntityBase> saveEntity; private Dictionary<ICommandBaseRepository, List<UpdatePartFieldModel>> changedPartFieldEntityList;
private Dictionary<ICommandBaseRepository, List<UpdateSingleFieldByIdsModel>> changedPartByIdsEntityList; private readonly IScopeDBFactory scopeDBFactory;
public UnitOfWorkImpl(IScopeDBFactory scopeDBFactory)
{ addedEntities = new Dictionary<ICommandBaseRepository, List<EntityBase>>();
changedEntities = new Dictionary<ICommandBaseRepository, List<EntityBase>>();
deletedEntities = new Dictionary<ICommandBaseRepository, List<object>>();
saveEntity = new Dictionary<ICommandBaseRepository, EntityBase>(); changedPartFieldEntityList = new Dictionary<ICommandBaseRepository, List<UpdatePartFieldModel>>();
changedPartByIdsEntityList = new Dictionary<ICommandBaseRepository, List<UpdateSingleFieldByIdsModel>>();
this.scopeDBFactory = scopeDBFactory;
} public void RegisterInsert(EntityBase entity, ICommandBaseRepository unitofWorkRepository)
{ if (!addedEntities.ContainsKey(unitofWorkRepository))
{
addedEntities.Add(unitofWorkRepository, new List<EntityBase>() { entity });
}
else
{
List<EntityBase> list = addedEntities[unitofWorkRepository];
if (!list.Contains(entity))
{
addedEntities[unitofWorkRepository].Add(entity); }
} } public void RegisterSave(EntityBase entity, ICommandBaseRepository unitofWorkRepository)
{ if (!saveEntity.ContainsKey(unitofWorkRepository))
{
saveEntity.Add(unitofWorkRepository, entity);
}
else
{
throw new Exception("不能重复添加");
} } public void RegisterUpdate(EntityBase entity, ICommandBaseRepository unitofWorkRepository)
{ if (!changedEntities.ContainsKey(unitofWorkRepository))
{
changedEntities.Add(unitofWorkRepository, new List<EntityBase>() { entity });
}
else
{
List<EntityBase> list = changedEntities[unitofWorkRepository]; if (!list.Contains(entity))
{
changedEntities[unitofWorkRepository].Add(entity); }
}
} public void RegisterUpdateByFields(EntityBase entity, IList<string> fields, ICommandBaseRepository unitofWorkRepository)
{
var updatePartModel = new UpdatePartFieldModel();
updatePartModel.Entity = entity;
updatePartModel.Fields = fields;
if (!changedPartFieldEntityList.ContainsKey(unitofWorkRepository))
{
changedPartFieldEntityList.Add(unitofWorkRepository, new List<UpdatePartFieldModel>() { updatePartModel });
}
else
{
List<UpdatePartFieldModel> list = changedPartFieldEntityList[unitofWorkRepository];
if (!list.Contains(updatePartModel))
{
changedPartFieldEntityList[unitofWorkRepository].Add(updatePartModel);
}
}
} public void RegisterUpdateSingleFieldByIds(IList<object> idList, KeyValuePair<string, object> column, ICommandBaseRepository unitofWorkRepository)
{ var updateSingleFieldByIdModel = new UpdateSingleFieldByIdsModel();
updateSingleFieldByIdModel.IdList = idList;
updateSingleFieldByIdModel.Column = column;
if (!changedPartByIdsEntityList.ContainsKey(unitofWorkRepository))
{
changedPartByIdsEntityList.Add(unitofWorkRepository, new List<UpdateSingleFieldByIdsModel>() { updateSingleFieldByIdModel });
}
else
{
List<UpdateSingleFieldByIdsModel> list = changedPartByIdsEntityList[unitofWorkRepository];
if (!list.Contains(updateSingleFieldByIdModel))
{
changedPartByIdsEntityList[unitofWorkRepository].Add(updateSingleFieldByIdModel);
}
}
} public void RegisterDelete(object id, ICommandBaseRepository unitofWorkRepository)
{ if (!deletedEntities.ContainsKey(unitofWorkRepository))
{
deletedEntities.Add(unitofWorkRepository, new List<object>() { id });
}
else
{
List<object> list = deletedEntities[unitofWorkRepository];
if (!list.Contains(id))
{
deletedEntities[unitofWorkRepository].Add(id); }
} } /// <summary>
/// 开启事务
/// </summary>
/// <returns></returns>
private DBTransaction BeginNewDBTransaction(CustomDatabase db)
{
var scopeTransaction = new DBTransaction(db);
return scopeTransaction;
} public async Task CommitAsync()
{
//获得db对象 一个请求db是同一个
var db = scopeDBFactory.GetScopeDb();
using (var scope = BeginNewDBTransaction(db))
{
///插入新增的实体
foreach (var repository in this.addedEntities.Keys)
{
var entityList = addedEntities[repository];
if (entityList.Count > 1)
{
await repository.InsertBatchAsync(entityList).ConfigureAwait(false);
}
else
{
await repository.InsertAsync(entityList[0]).ConfigureAwait(false);
}
} ///保存实体 有则更新 无则删除
foreach (var repository in this.saveEntity.Keys)
{
var entity = saveEntity[repository];
await repository.SaveAsync(entity).ConfigureAwait(false);
} //更新需要修改的实体
foreach (var repository in this.changedEntities.Keys)
{
var entityList = changedEntities[repository];
if (entityList.Count > 1)
{
await repository.UpdateBatchAsync(entityList).ConfigureAwait(false);
}
else
{
await repository.UpdateAsync(entityList[0]).ConfigureAwait(false);
}
} ///更新根据字段更新的实体
foreach (var repository in this.changedPartFieldEntityList.Keys)
{
var updateModelList = changedPartFieldEntityList[repository];
foreach (var updateModel in updateModelList)
{
await repository.UpdateAsync(updateModel.Entity, updateModel.Fields).ConfigureAwait(false);
}
} ///更新根据id集合更新的数据实体
foreach (var repository in this.changedPartByIdsEntityList.Keys)
{
var updateModelList = changedPartByIdsEntityList[repository];
foreach (var updateModel in updateModelList)
{
await repository.UpdateSingleFieldByIdsAsync(updateModel.IdList, updateModel.Column).ConfigureAwait(false);
}
} ///删除实体
foreach (var repository in this.deletedEntities.Keys)
{
var entityList = deletedEntities[repository];
if (entityList.Count > 1)
{
await repository.SoftDeleteBatchAsync(entityList).ConfigureAwait(false);
}
else
{
await repository.SoftDeleteAsync(entityList[0]).ConfigureAwait(false);
} }
scope.Complete();
addedEntities.Clear();
changedEntities.Clear();
deletedEntities.Clear();
saveEntity.Clear();
changedPartFieldEntityList.Clear();
changedPartByIdsEntityList.Clear();
}
}
}
}
namespace test.DAL
{
internal class UpdatePartFieldModel
{ public EntityBase Entity { get; set; } public IList<string> Fields { get; set; } } internal class UpdateSingleFieldByIdsModel
{ public IList<object> IdList { get; set; } public KeyValuePair<string, object> Column { get; set; } }
}
针对批量删除、批量修改等各种操作,根据各个业务多一层封装UnitOfWork,减少提交工作单元时各种循环,不想要的也可以去掉
以customer业务表为例代码
如下:
namespace test.IDAL
{
public interface ICommandCustomerRepository : ICommandBaseRepository
{ }
}
客户服务仓储单元接口
namespace test.IDAL
{
public interface ICustomerUnitOfWork
{
void RegisterInsert(CustomerEntity entity); void RegisterInsertBatch(IList<CustomerEntity> entities); void RegisterUpdate(CustomerEntity entity); void RegisterUpdateBatch(IList<CustomerEntity> entities); void RegisterUpdateByFields(CustomerEntity entity,List<string> fields); void RegisterUpdateSingleFieldByIds(IList<long> idList, KeyValuePair<string, object> column); void RegisterDelete(long id); void RegisterDeleteBatch(IList<long> idList); Task CommitAsync();
}
}
客户实体
namespace test.Entity
{
/// <summary>
/// 基础数据-客户信息
/// </summary>
[MyTableName("Customer")]
[MyPrimaryKey("Id", AutoIncrement = false)]
public class CustomerEntity : EntityBase
{
/// <summary>
/// 客户名称
/// </summary>
public string Name { get; set; } /// <summary>
/// 客户code
/// </summary>
///
public string Code { get; set; } /// <summary>
/// 是否可用 0 否 1是
/// </summary>
public bool? IsEnabled { get; set; } /// <summary>
/// 邮箱
/// </summary>
public string Email { get; set; } /// <summary>
/// 传真
/// </summary>
public string Fax { get; set; } /// <summary>
/// 联系人
/// </summary>
public string ContactPerson { get; set; } /// <summary>
/// 联系人电话
/// </summary>
public string ContactTelphone { get; set; } /// <summary>
/// 地址
/// </summary>
public string Address { get; set; } /// <summary>
/// 备注
/// </summary>
public string Remark { get; set; } } }
客户服务工作单元实现
namespace test.DAL
{
internal class CustomerUnitOfWorkImpl:ICustomerUnitOfWork , IAutoInject
{ private readonly IUnitOfWork unitOfWork;
private readonly ICommandCustomerRepository commandRepository; public CustomerUnitOfWorkImpl(ICommandCustomerRepository commandRepository, IUnitOfWork unitOfWork)
{
this.commandRepository = commandRepository; this.unitOfWork = unitOfWork;
} public void RegisterInsert(CustomerEntity entity)
{
unitOfWork.RegisterInsert(entity, commandRepository);
} public void RegisterInsertBatch(IList<CustomerEntity> entities)
{
foreach (var entity in entities)
{
unitOfWork.RegisterInsert(entity, commandRepository);
} } public void RegisterUpdate(CustomerEntity entity)
{
unitOfWork.RegisterUpdate(entity, commandRepository); } public void RegisterUpdateBatch(IList<CustomerEntity> entities)
{
foreach (var entity in entities)
{
unitOfWork.RegisterUpdate(entity, commandRepository);
}
} public void RegisterUpdateByFields(CustomerEntity entity, List<string> fields)
{
unitOfWork.RegisterUpdateByFields(entity, fields, commandRepository);
} public void RegisterUpdateSingleFieldByIds(IList<long> idList, KeyValuePair<string, object> column)
{
unitOfWork.RegisterUpdateSingleFieldByIds(idList, column, commandRepository);
} public void RegisterDelete(long entity)
{
unitOfWork.RegisterDelete(entity, commandRepository);
} public void RegisterDeleteBatch(IList<long> entities)
{
foreach (var entity in entities)
{
unitOfWork.RegisterDelete(entity, commandRepository);
} }
public async Task CommitAsync()
{
await unitOfWork.CommitAsync().ConfigureAwait(false);
}
}
}
客户服务接口
namespace test.IBLL.Basic
{
public interface ICommandCustomerService
{
/// <summary>
/// 插入单个实体
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
Task<HttpResponseResultModel<long>> InsertAsync(CustomerEntity entity,bool isCommit = true); /// <summary>
/// 批量插入实体
/// </summary>
/// <param name="entityList"></param>
/// <returns></returns>
Task<HttpResponseResultModel<bool>> InsertBatchAsync(List<CustomerEntity> entityList,bool isCommit = true); /// <summary>
/// 根据主键更新实体
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
Task<HttpResponseResultModel<bool>> UpdateAsync(CustomerEntity entity,bool isCommit = true); /// <summary>
/// 更新实体的部分字段
/// </summary>
/// <param name="entity"></param>
/// <param name="columns"></param>
/// <returns></returns>
Task<HttpResponseResultModel<bool>> UpdateFieldsAsync(CustomerEntity entity, List<string> fields, bool isCommit = true); /// <summary>
/// 根据id集合更新某个字段更新
/// </summary>
/// <param name="idList"></param>
/// <param name="column"></param>
/// <param name="isCommit"></param>
/// <returns></returns>
Task<HttpResponseResultModel<bool>> UpdateSingleFieldByIdsAsync(List<long> idList, KeyValuePair<string, object> column, bool isCommit = true); /// <summary>
/// 根据主键批量更新实体
/// </summary>
/// <param name="entityList">实体集合</param>
/// <returns></returns>
Task<HttpResponseResultModel<bool>> UpdateBatchAsync(List<CustomerEntity> entityList,bool isCommit = true); /// <summary>
/// 根据根据主键删除
/// </summary>
/// <param name="id">主键</param>
/// <returns></returns>
Task<HttpResponseResultModel<bool>> DeleteAsync(long id,bool isCommit = true); /// <summary>
/// 批量删除 根据主键
/// </summary>
/// <param name="idList">主键集合</param>
/// <returns></returns>
Task<HttpResponseResultModel<bool>> DeleteBatchAsync(IList<long> idList,bool isCommit = true); /// <summary>
/// 保存实体,有则更新,无则新增
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
Task<HttpResponseResultModel<bool>> SaveAsync(CustomerEntity entity,bool isCommit = true);
}
}
客户服务接口实现
namespace test.BLL.Basic
{
internal class CommandCustomerServiceImpl : ICommandCustomerService, IAutoInject
{
private readonly ICustomerUnitOfWork unitOfWork; public CommandCustomerServiceImpl(ICustomerUnitOfWork unitOfWork)
{
this.unitOfWork = unitOfWork;
} #region 插入 /// <summary>
/// 插入单个实体
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
public async Task<HttpResponseResultModel<long>> InsertAsync(CustomerEntity entity,bool isCommit = true)
{
HttpResponseResultModel<long> httpResponseResultModel = new HttpResponseResultModel<long> { IsSuccess = false };
unitOfWork.RegisterInsert(entity);
if (isCommit)
{
await CommitAsync();
}
httpResponseResultModel.BackResult = entity.Id;
httpResponseResultModel.IsSuccess = true;
return httpResponseResultModel;
} /// <summary>
/// 批量插入实体
/// </summary>
/// <param name="entityList"></param>
/// <returns></returns>
public async Task<HttpResponseResultModel<bool>> InsertBatchAsync(List<CustomerEntity> entityList,bool isCommit = true)
{
HttpResponseResultModel<bool> httpResponseResultModel = new HttpResponseResultModel<bool> { IsSuccess = false };
unitOfWork.RegisterInsertBatch(entityList);
if (isCommit)
{
await CommitAsync();
}
httpResponseResultModel.BackResult = true;
httpResponseResultModel.IsSuccess = true;
return httpResponseResultModel;
} #endregion #region 更新
/// <summary>
/// 根据主键更新实体
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
public async Task<HttpResponseResultModel<bool>> UpdateAsync(CustomerEntity entity,bool isCommit = true)
{
HttpResponseResultModel<bool> httpResponseResultModel = new HttpResponseResultModel<bool> { IsSuccess = false };
unitOfWork.RegisterUpdate(entity);
if (isCommit)
{
await CommitAsync();
}
httpResponseResultModel.IsSuccess = true;
return httpResponseResultModel;
} /// <summary>
/// 批量更新实体
/// </summary>
/// <param name="entityList"></param>
/// <returns></returns>
public async Task<HttpResponseResultModel<bool>> UpdateBatchAsync(List<CustomerEntity> entityList,bool isCommit = true)
{
HttpResponseResultModel<bool> httpResponseResultModel = new HttpResponseResultModel<bool> { IsSuccess = false };
unitOfWork.RegisterUpdateBatch(entityList);
if (isCommit)
{
await CommitAsync();
}
httpResponseResultModel.IsSuccess = true;
return httpResponseResultModel;
} /// <summary>
/// 更新实体的部分字段
/// </summary>
/// <param name="entity"></param>
/// <param name="columns"></param>
/// <returns></returns>
public async Task<HttpResponseResultModel<bool>> UpdateFieldsAsync(CustomerEntity entity, List<string> fields, bool isCommit = true)
{
HttpResponseResultModel<bool> httpResponseResultModel = new HttpResponseResultModel<bool> { IsSuccess = false };
unitOfWork.RegisterUpdateByFields(entity, fields);
if (isCommit)
{
await CommitAsync(); }
httpResponseResultModel.IsSuccess = true;
return httpResponseResultModel;
} /// <summary>
/// 根据id集合更新某个字段更新
/// </summary>
/// <param name="idList"></param>
/// <param name="column"></param>
/// <param name="isCommit"></param>
/// <returns></returns>
public async Task<HttpResponseResultModel<bool>> UpdateSingleFieldByIdsAsync(List<long> idList, KeyValuePair<string, object> column, bool isCommit = true)
{
HttpResponseResultModel<bool> httpResponseResultModel = new HttpResponseResultModel<bool> { IsSuccess = false };
unitOfWork.RegisterUpdateSingleFieldByIds(idList, column);
if (isCommit)
{
await CommitAsync();
}
httpResponseResultModel.IsSuccess = true;
return httpResponseResultModel;
} #endregion #region 删除 /// <summary>
/// 根据根据主键删除
/// </summary>
/// <param name="id">主键</param>
/// <returns></returns>
public async Task<HttpResponseResultModel<bool>> DeleteAsync(long id,bool isCommit = true)
{
HttpResponseResultModel<bool> httpResponseResultModel = new HttpResponseResultModel<bool> { IsSuccess = false };
unitOfWork.RegisterDelete(id);
if (isCommit)
{
await CommitAsync();
}
httpResponseResultModel.IsSuccess = true;
return httpResponseResultModel;
} /// <summary>
/// 批量删除 根据主键
/// </summary>
/// <param name="idList">主键集合</param>
/// <returns></returns>
public async Task<HttpResponseResultModel<bool>> DeleteBatchAsync(IList<long> idList,bool isCommit = true)
{
HttpResponseResultModel<bool> httpResponseResultModel = new HttpResponseResultModel<bool> { IsSuccess = false };
unitOfWork.RegisterDeleteBatch(idList);
if (isCommit)
{
await CommitAsync();
} httpResponseResultModel.IsSuccess = true;
return httpResponseResultModel; } #endregion /// <summary>
/// 保存实体,有则更新,无则新增
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
public async Task<HttpResponseResultModel<bool>> SaveAsync(CustomerEntity entity,bool isCommit = true)
{
HttpResponseResultModel<bool> httpResponseResultModel = new HttpResponseResultModel<bool> { IsSuccess = false }; return httpResponseResultModel;
} #region 事务 /// <summary>
/// 事务
/// </summary>
/// <returns></returns>
public async Task CommitAsync()
{
await unitOfWork.CommitAsync().ConfigureAwait(false);
}
#endregion }
}
using System.Net; namespace test.Core
{ /// <summary>
/// http请求结果类
/// </summary>
/// <typeparam name="T"></typeparam>
public class HttpResponseResultModel<T>
{
/// <summary>
/// http码
/// </summary>
public HttpStatusCode HttpStatusCode { get; set; } /// <summary>
/// 是否成功
/// </summary>
public bool IsSuccess { get; set; } /// <summary>
/// 返回结果
/// </summary>
public T BackResult { get; set; } /// <summary>
/// 错误信息
/// </summary>
public string ErrorMessage { get; set; } /// <summary>
/// 异常信息
/// </summary>
public string ExceptionMessage { get; set; }
}
}
请尝试网页搜索
.NET Core 工作单元unitofwork 实现,基于NPOCO的更多相关文章
- Asp.Net Core 工作单元 UnitOfWork UOW
Asp.Net Core 工作单元示例 来自 ABP UOW 去除所有无用特性 代码下载 : 去除所有无用特性版本,原生AspNetCore实现 差不多 2278 行代码: 链接:https://pa ...
- .net core2.x - 关于工作单元(UnitOfWork) 模式
概要:在搭建框架,顺手说下写下,关于unitofwork,可能你理解了,可能你还不理解,可能与不可能不是重点,重点是感兴趣就看看吧. 1.工作单元(unitofowork)是什么(后面简写uow)? ...
- ABP官方文档翻译 3.6 工作单元
工作单元 介绍 ABP中的连接和事务管理 传统的工作单元方法 控制工作单元 UnitOfWork特性 IUnitOfWorkManager 工作单元详情 禁用工作单元 无事务工作单元 一个工作单元方法 ...
- ABP框架 - 工作单元
文档目录 本节内容: 简介 在ABP中管理连接和事务 约定的工作单元 UnitOfWork 特性 IUnitOfWorkManager 工作单元详情 禁用工作单元 非事务性工作单元 工作单元方法调用另 ...
- ABP的工作单元
http://www.aspnetboilerplate.com/Pages/Documents/Unit-Of-Work 工作单元位于领域层. ABP的数据库连接和事务处理: 1,仓储类 ASP ...
- 手工搭建基于ABP的框架 - 工作单元以及事务管理
一个业务功能往往不只由一次数据库请求(或者服务调用)实现.为了功能的完整性,我们希望如果该功能执行一半时出错,则撤销前面已执行的改动.在数据库层面上,事务管理实现了这种完整性需求.在ABP中,一个完整 ...
- 知识全聚集 .Net Core 技术突破 | 简单说说工作单元
知识全聚集 .Net Core 技术突破 | 简单说说工作单元 教程 01 | 模块化方案一 02 | 模块化方案二 其他教程预览 分库分表项目实战教程 Git地址: https://github.c ...
- 工作单元模式(UnitOfWork)学习总结
工作单元的目标是维护变化的对象列表.使用IUnitOfWorkRepository负责对象的持久化,使用IUnitOfWork收集变化的对象,并将变化的对象放到各自的增删改列表中, 最后Commit, ...
- 基于DDD的.NET开发框架 - ABP工作单元(Unit of Work)
返回ABP系列 ABP是“ASP.NET Boilerplate Project (ASP.NET样板项目)”的简称. ASP.NET Boilerplate是一个用最佳实践和流行技术开发现代WEB应 ...
随机推荐
- Dubbo对Spring Cloud说:来老弟,我要拥抱你
项目地址 https://github.com/yinjihuan/kitty-cloud 前言 Kitty Cloud 开源后有以为朋友在 GitHub 上给我提了一个 issues,问为什么项目中 ...
- 用实例理解k8s群集(干货)
一些概念: 1. pods是一组容器的集合,以pods为单位来管理,共享PID,网络IP和CUTS命名空间: 2. 容器共享存储卷:用yml文件来定义容器,是k8s里的最小单位. 3.本实验要先准备好 ...
- jdk1.8的一些特性
一.jdk1.8的特性: Lambda表达式 函数式接口 方法引用 接口的默认方法和静态方法 Optional Streams 并行数组 新时间日期API 二.Lambda表达式: Lambda 表达 ...
- 常用的code snipper
Xcode 10.2.1 版本,自动代码提示功能延迟很大,很多情况下代码提示甚至会无效,但是code snippet 唤起的响应很快,从提高效率的情况考虑,即使系统提供的代码提示制作成code sni ...
- UVA10529 Dumb Bones (完成度:40%)
题目链接:https://vjudge.net/problem/UVA-10529 知识点: 概率与期望,DP. 题目大意: 现要放置 \(n\) 个多米诺骨牌,且每放置一块多米诺骨牌有 \(P_l\ ...
- 【MySQL】详细说下MySQL删除数据的过程是什么样的?
drop table 这里先介绍一下[InnoDB]存储表空间概念: Innodb存储引擎,可将所有的数据库数据存放于[ibdata1]的共享表空间:也可以将每张表存放于独立的.idb文件的独立表空间 ...
- 模板技术:JSP、Thymeleaf之间的比较学习
JSP Thymeleaf 可以写java代码的html JSP的替代品 执行过程 页面元素 include 跳转 cookie session 作用域 隐式对象 JS ...
- 25-12 空值处理(null值)
--------------------空值处理--------------------- select * from TblStudent --查询所有年龄是null的同学学习信息 --null值无 ...
- 使用vue2.0创建的项目的步骤
1.由于vue项目依赖 node.js npm 需要先安装. 若没有请先安装,请百度 //检查是否有node.js npm vue win+r 输入cmd 输入node -v 回车 会出 ...
- 当 RocketMQ 遇上 Serverless,会碰撞出怎样的火花?
作者 | 元毅 阿里巴巴高级开发工程师 阿里巴巴云原生公众号后台回复 Knative,免费下载<Knative 云原生应用开发指南>电子书! 想必大家都比较了解 RocketMQ 消息服 ...