zoukankan      html  css  js  c++  java
  • .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; }
        }
    }
    
      没有英汉互译结果
      请尝试网页搜索
      没有英汉互译结果
      请尝试网页搜索

  • 相关阅读:
    C#概述
    作为一个程序员小小感悟!!
    c# 合并两个DataTable
    C# FastReport .NET打印
    c# System.Net.Sockets =》TcpListener用法
    开博第一章
    Vue 报错 Uncaught (in promise)
    ASP.NET MVC 中的过滤器
    SpringBoot 打包成war
    SprintBoot 实现上传下载
  • 原文地址:https://www.cnblogs.com/binbinxu/p/13061726.html
Copyright © 2011-2022 走看看