EF Core 6 增删改查、 异步事务

.net 6 增删改查、 异步事务

using AutoMapper;
using AutoMapper.QueryableExtensions;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using wms.Infrastructure;
using wms.Model.Dtos;
using wms.Model.Entities;
using wms.Repository;

namespace wms.Service
{

    public class OrderConsolidatePackageService : IOrderConsolidatePackageService
    {

        private readonly IOrderConsolidatePackageRepository repository;
        private readonly IUnitOfWork unitOfWork;
        private readonly IMapper mapper;
        private readonly WmsDataContext dataContext;
        public OrderConsolidatePackageService(IOrderConsolidatePackageRepository repository, IUnitOfWork unitOfWork, IMapper mapper, WmsDataContext dataContext)
        {
            this.repository = repository;
            this.unitOfWork = unitOfWork;
            this.mapper = mapper;
            this.dataContext = dataContext;
        }


        public async Task<OrderConsolidatePackageDto?> Add(OrderConsolidatePackageBaseDto info)
        {


            var dbInfo = this.mapper.Map<TOrderConsolidatePackage>(info);


            this.repository.Insert(dbInfo);
            await this.unitOfWork.CommitAsync();


            // return this.mapper.Map<StateDto>(dbInfo);
            return await GetInfo(dbInfo.OrderConPackageId);
        }

        public async Task Delete(long id)
        {
            using (var trans = dataContext.Database.BeginTransaction())
            {
                try
                {
                    var item = await this.repository.Query()
                        .Where(d => d.OrderConPackageId == id).SingleOrDefaultAsync();

                    if (item != null)
                    {
                        repository.Delete(item);
                        await this.unitOfWork.CommitAsync();

                        await trans.CommitAsync();
                    }
                }
                catch (Exception)
                {
                    await trans.RollbackAsync();
                    throw;
                }
            }
        }



        public async Task DeleteList(ReqestDeleteListModel<long> info)
        {
            using (var trans = dataContext.Database.BeginTransaction())
            {
                try
                {
                    var delList = await this.repository.Query()
                        .Where(d => info.ids.Contains(d.OrderConPackageId)).ToListAsync();
                    if (delList.Count > 0)
                    {
                        foreach (var item in delList)
                        {

                            if (item != null)
                            {

                                repository.Delete(item);
                                await this.unitOfWork.CommitAsync();


                            }

                        }


                        await trans.CommitAsync();
                    }
                }
                catch (Exception)
                {
                    await trans.RollbackAsync();
                    throw;
                }
            }
        }



        public async Task<OrderConsolidatePackageDto?> GetInfo(long id)
        {
            // var info = await this.repository.Query().Include(d => d.TStateTrans.Where(d => d.LanguageId == languageId)).Where(d => d.StateId == id).SingleOrDefaultAsync();
            //this.mapper.Map<StateDto?>(info);
            var info = await GetQueryable().Where(d => d.OrderConPackageId == id).SingleOrDefaultAsync(); ;
            return info;
        }

        public IQueryable<OrderConsolidatePackageDto> GetQueryable()
        {
            var query = repository.Query().Include(d=>d.Order).Include(d=>d.PgcodeNavigation);
            return query.ProjectTo<OrderConsolidatePackageDto>(mapper.ConfigurationProvider);

        }

        public async Task<OrderConsolidatePackageDto?> Update(OrderConsolidatePackageBaseDto info)
        {
            var m = await repository.Query().Where(d => d.OrderConPackageId == info.OrderConPackageId).SingleOrDefaultAsync();
            if (m == null)
            {
                return null!;
            }

            m.Pgcode = info.Pgcode;
            m.PackageName = info.PackageName;
            m.LengthImperial = info.LengthImperial;
            m.WidthImperial = info.WidthImperial;
            m.HeightImperial = info.HeightImperial;
            m.GrossWeightImperial = info.GrossWeightImperial;
            m.LengthMetric = info.LengthMetric;
            m.WidthMetric = info.WidthMetric;
            m.HeightMetric = info.HeightMetric;
            m.GrossWeightMetric = info.GrossWeightMetric;
            m.PackageWeightMetric = info.PackageWeightMetric;
            m.VolumeOccupiedRatio = info.VolumeOccupiedRatio;
            m.PackageWeightImperial = info.PackageWeightImperial;
            m.NetWeightMetric = info.NetWeightMetric;
            m.NetWeightImperial = info.NetWeightImperial;
           
            repository.Update(m);
            await this.unitOfWork.CommitAsync();

            await UpdateGrossWeight(m.OrderConPackageId);
            return await GetInfo(info.OrderId);
        }

        public async Task UpdateGrossWeight(long orderConPackageId)
        {
            var m = await repository.Query().Include(d=>d.TConsolidatepackagePackgeRels).ThenInclude(d=>d.OrderPackage).Where(d => d.OrderConPackageId == orderConPackageId).SingleOrDefaultAsync();

            if (m != null)
            {
                var list = m.TConsolidatepackagePackgeRels.ToList();
                var grossWeightImperial = list.Sum(d => d.OrderPackage.GrossWeightImperial * d.Quantity);
                var grossWeightMetric = list.Sum(d => d.OrderPackage.GrossWeightMetric * d.Quantity);
                m.GrossWeightImperial = m.PackageWeightImperial + grossWeightImperial;
                m.GrossWeightMetric = m.PackageWeightMetric + grossWeightMetric;

                await this.unitOfWork.CommitAsync();
            }

        }

        public async Task ClearAll(long orderId)
        {
            using (var trans = dataContext.Database.BeginTransaction())
            {
                try
                {
                    var delList = await this.repository.Query()
                        .Where(d => d.OrderId == orderId).ToListAsync();
                    if (delList.Count > 0)
                    {
                        foreach (var item in delList)
                        {

                            if (item != null)
                            {

                                repository.Delete(item);
                                await this.unitOfWork.CommitAsync();


                            }

                        }


                        await trans.CommitAsync();
                    }
                }
                catch (Exception)
                {
                    await trans.RollbackAsync();
                    throw;
                }
            }
        }
    }


}

 

对比 .net 4.5.2版本事务

        public int WeatherHourlyAddRange(List<WeatherHourly> weatherHourlyList)
        {
            if (weatherHourlyList.Count() == 0) return 0;
            int num = 0;

            if (weatherHourlyList.Count > 0)
            {
              

                using (var db = new EcologyServiceEntities())
                {
                    var tran = db.Database.BeginTransaction();//开启事务
                    try
                    {
                        db.WeatherHourly.AddRange(weatherHourlyList);
                        num = db.SaveChanges();
                        tran.Commit();  //必须调用Commit(),不然数据不会保存
           
                    }
                    catch (Exception ex)
                    {
                        tran.Rollback(); //出错就回滚
                        LogManage.Error("小时数据报错", ex);

                        //若重复错误,则逐条遍历。
                        while (ex.InnerException != null)
                        {
                            ex = ex.InnerException;
                            if (ex.Message.Contains("IX_"))
                            {
                                foreach (var myObj in weatherHourlyList)
                                {
                                    try
                                    {
                                        using (var db3 = new EcologyServiceEntities())
                                        {
                                            db3.WeatherHourly.Add(myObj);
                                            db3.SaveChanges();
                                        }
                                    }
                                    catch (Exception ex2)
                                    {


                                    }
                                }
                            }
                        } 
                    }
                }
            }
            return num;
        }

 

posted @ 2023-03-17 10:47  hao_1234_1234  阅读(146)  评论(0编辑  收藏  举报