.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应 ...
随机推荐
- 【数论基础】素数判定和Miller Rabin算法
判断正整数p是否是素数 方法一 朴素的判定
- 1、Fiddler基础
1.抓取https请求 前言 fiddler是一个很好的抓包工具,默认是抓http请求的,对于pc上的https请求,会提示网页不安全,这时候需要在浏览器上安装证书. 一.网页不安全 1.用fiddl ...
- MySQL 入门(5):复制
摘要 在这篇文章中,我将从MySQL为什么需要主从复制开始讲起,然后会提到MySQL复制的前提,bin log. 在这里会说明三种格式的bin log分别会有什么优缺点. 随后会讲到主从延迟方面的问题 ...
- 【Jenkins学习】【第二节】 jenkins构建触发器定时任务
一.定时构建 Build periodically:定时执行构建任务,不管远程代码分支上的代码是否发生变化,都执行一次构建. 语法:* * * * *(五颗星,中间用空格隔开) 第一个:分钟,取值0~ ...
- python实现登录密码重置简易操作
需求: 1.用户输入密码正确登录 2.用户输入密码错误退出并调用函数继续输入 3.用户输入密码符合原先给定的一个值时,允许用户重置密码,并且可以用新密码登录 4.输入三次后禁止输入 虽然贴别的简单,但 ...
- DPDK Mbuf Library(学习笔记)
1 Mbuf库 Mbuf库提供了分配和释放缓冲区(mbufs)的功能,DPDK应用程序可以使用这些mbufs来存储消息缓冲. 消息缓冲存储在内存池中,使用Mempool库. 数据结构rte_mbuf通 ...
- 王艳 201771010127《面向对象程序设计(java)》第三周学习总结
一:理论知识总结: 第一章:主要概述了java相比其他程序设计语言(如C语言.c++)之间的不同性能.为我们揭示了java这种语言的设计初衷一节截至目前java语言达到的效果.另外,还简要介绍了jav ...
- CF918C The Monster
题目链接:http://codeforces.com/contest/918/problem/C 知识点: 贪心 解题思路: 枚举起点(当起点就是\(')'\)时直接跳过)并在此基础上遍历字符串,用一 ...
- 基于 abp vNext 和 .NET Core 开发博客项目 - 异常处理和日志记录
在开始之前,我们实现一个之前的遗留问题,这个问题是有人在GitHub Issues(https://github.com/Meowv/Blog/issues/8)上提出来的,就是当我们对Swagger ...
- spring的mybatis-puls 配置,增删改查操作,分页
pom <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.or ...