1. 程式人生 > >.NET Core 工作單元unitofwork 實現,基於NPOCO

.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; }
    }
}

 

 

 

 

Test 詳細X   沒有英漢互譯結果
  請嘗試網頁搜尋 IAutoInject 詳細X   沒有英漢互譯結果
  請嘗試網頁搜尋