using EFCore.BulkExtensions; using Magicodes.ExporterAndImporter.Core.Models; using Magicodes.ExporterAndImporter.Excel; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore.Storage; using Microsoft.Extensions.Configuration; using OfficeOpenXml.FormulaParsing.Excel.Functions.Math; using OfficeOpenXml.FormulaParsing.Excel.Functions.Text; using Omu.ValueInjecter; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Threading.Tasks; using System.Transactions; using TaskManager.Entity; using TaskManager.Entity.Entitys; using TaskManager.EntityFramework; using TaskManager.EntityFramework.Repository; using Wood.Service.Controllers; using Wood.Util; namespace Wood.Service.Datas { public class SupplierProProcessEquipmentDtService : NormalBaseController { const string _taskName = "工艺装备"; private readonly IRepository _taskSubRepository; private readonly IRepository _supplierProProcessEquipmentRepository; private readonly IRepository _taskConfigureRepository; private readonly CommonService _commonService; public SupplierProProcessEquipmentDtService(JobDbContext context, IServiceProvider builder, IConfiguration configuration, IRepository repository, IRepository taskSubRepository, IRepository supplierProProcessEquipmentRepository, IRepository taskConfigureRepository, CommonService commonService) : base(context, builder, configuration, repository) { _taskSubRepository = taskSubRepository; _supplierProProcessEquipmentRepository = supplierProProcessEquipmentRepository; _taskConfigureRepository = taskConfigureRepository; _taskSubRepository.SetDbContext(_context); _supplierProProcessEquipmentRepository.SetDbContext(_context); _taskConfigureRepository.SetDbContext(_context); _commonService = commonService; } [HttpPost] [Route("import")] public override async Task Import(IFormFile file) { if (file == null || file.Length == 0) { return NotFound(); } MemoryStream memStream = new MemoryStream(); await file.CopyToAsync(memStream); var importer = new ExcelImporter(); ImportResult impResult = await importer.Import(memStream); if (impResult.HasError) { StringBuilder sb = new StringBuilder(); foreach (var rowErr in impResult.RowErrors) { string temp = string.Join(";", rowErr.FieldErrors.Select(itm => $"第{rowErr.RowIndex}行:{itm.Key}-{itm.Value}")); sb.AppendLine(temp); } foreach (var templateErr in impResult.TemplateErrors) { string temp = $"列名:{templateErr.RequireColumnName},错误信息:{templateErr.Message}"; sb.AppendLine(temp); } throw new Exception(sb.ToString()); } var entityLst = impResult.Data.ToList(); // 校验数据长度 var validationErrors = ValidationHelper.ValidateDataLength(entityLst, _context); if (validationErrors.Any()) { throw new Exception("数据校验失败:" + string.Join(", ", validationErrors)); } using var transaction = _context.Database.BeginTransaction(); var tran = transaction.GetDbTransaction(); try { #region 数据库操作 //添加任务 TaskSub taskSubObj = _commonService.BuildTaskSub(entityLst.Count, _taskName); await _taskSubRepository.AddAsync(taskSubObj); //添加任务明细 List eqs = new List(); foreach (var empDtObj in entityLst) { empDtObj.SupplierCode = VendCode; empDtObj.ReadState = true; SUPPLIER_PRO_PROCESS_EQUIPMENT empObj = new SUPPLIER_PRO_PROCESS_EQUIPMENT(); empObj.InjectFrom(empDtObj); empObj.TaskId = taskSubObj.TaskId; empObj.SupplierCode = VendCode; empObj.ReadState = true; eqs.Add(empObj); // await _supplierProProcessEquipmentRepository.AddAsync(empObj); } _context.BulkInsert(eqs); //_context.BulkMerge(entityLst, // itm=> itm.SupplierCode, // itm=> itm.CheryProductNo, // itm=> itm.DeviceCode, // itm=> itm.DeviceType // ); // _context.BulkMerge(entityLst, options => { options.ColumnPrimaryKeyExpression = itm => new { itm.SupplierCode, itm.CheryProductNo, itm.DeviceCode, itm.DeviceType }; options.Transaction = tran; }); foreach (var empDtObj in entityLst) { empDtObj.SupplierCode = VendCode; //以供应商代码+奇瑞零件号+工艺编码+工艺版本为唯一数据,做新增或者更新存储 var firstObj = _context.Set().FirstOrDefault( itm => itm.SupplierCode == empDtObj.SupplierCode && itm.CheryProductNo == empDtObj.CheryProductNo && itm.DeviceCode == empDtObj.DeviceCode && itm.DeviceType == empDtObj.DeviceType ); if (firstObj == null) { var ret = await base.Create(empDtObj); } else { empDtObj.UId = firstObj.UId; empDtObj.CreationTime = CommonHelper.CurrentTime; var ret = await base.Update(empDtObj); } } #endregion transaction.Commit(); return Ok(true); } catch (Exception ex) { transaction.Rollback(); throw new Exception("方法体执行报错,事务回滚:" + ex.Message); } } public override async Task> Create(SUPPLIER_PRO_PROCESS_EQUIPMENT_DT entity) { using var transaction = _context.Database.BeginTransaction(); var tran = transaction.GetDbTransaction(); try { //添加任务 TaskSub taskSubObj = _commonService.BuildTaskSub(1, _taskName); await _taskSubRepository.AddAsync(taskSubObj); entity.SupplierCode = VendCode; entity.ReadState = true; entity.WriteState = false; entity.TaskId = taskSubObj.TaskId; //添加任务明细 SUPPLIER_PRO_PROCESS_EQUIPMENT empObj = new SUPPLIER_PRO_PROCESS_EQUIPMENT(); empObj.SupplierCode = entity.SupplierCode; empObj.SupplierName = entity.SupplierName; empObj.CheryProductNo = entity.CheryProductNo; empObj.CheryProductName = entity.CheryProductName; empObj.VendorProductNo = entity.VendorProductNo; empObj.VendorProductName = entity.VendorProductName; empObj.DeviceType = entity.DeviceType; empObj.DeviceCode = entity.DeviceCode; empObj.DeviceName = entity.DeviceName; empObj.Manufacturer = entity.Manufacturer; empObj.ModelNumber = entity.ModelNumber; empObj.SerialNumber = entity.SerialNumber; empObj.ProductionDate = entity.ProductionDate; empObj.Material = entity.Material; empObj.CurrentLocation = entity.CurrentLocation; empObj.DeviceStatus = entity.DeviceStatus; empObj.CavityCount = entity.CavityCount; empObj.MoldSize = entity.MoldSize; empObj.DesignLifeUnits = entity.DesignLifeUnits; empObj.DesignLifeValue = entity.DesignLifeValue; empObj.CurrentUsageCount = entity.CurrentUsageCount; empObj.OverhaulCount = entity.OverhaulCount; empObj.CoolingChannelLayout = entity.CoolingChannelLayout; empObj.DetectionAccuracy = entity.DetectionAccuracy; empObj.CalibrationDate = entity.CalibrationDate; empObj.CalibrationDueDays = entity.CalibrationDueDays; empObj.ToleranceRange = entity.ToleranceRange; empObj.WearThreshold = entity.WearThreshold; empObj.DetectionRange = entity.DetectionRange; empObj.UnitType = entity.UnitType; empObj.SupplierCode = VendCode; empObj.TaskId = taskSubObj.TaskId; empObj.ReadState = true; await _context.AddAsync(empObj); var firstObj = _context.Set().FirstOrDefault( itm => itm.SupplierCode == entity.SupplierCode && itm.CheryProductNo == entity.CheryProductNo && itm.DeviceCode == entity.DeviceCode && itm.DeviceType == entity.DeviceType ); if (firstObj == null) { var ret = await base.Create(entity); } else { throw new Exception("数据库已经存在,不能重复插入"); } // await _context.BulkInsertAsync(new List() { empObj }); // _context.BulkMerge(new List { entity }, //itm => itm.SupplierCode, //itm => itm.CheryProductNo, //itm => itm.DeviceCode, //itm => itm.DeviceType // ); _context.SaveChanges(); transaction.Commit(); return Ok(true); } catch (Exception ex) { transaction.Rollback(); throw new Exception("方法体执行报错,事务回滚:" + ex.Message); } } public override async Task Update(SUPPLIER_PRO_PROCESS_EQUIPMENT_DT entity) { using var transaction = _context.Database.BeginTransaction(); var tran = transaction.GetDbTransaction(); try { #region 数据库操作 //添加任务 TaskSub taskSubObj = _commonService.BuildTaskSub(1, _taskName); await _taskSubRepository.AddAsync(taskSubObj); entity.SupplierCode = VendCode; entity.ReadState = true; entity.WriteState = false; entity.TaskId = taskSubObj.TaskId; //添加任务明细 SUPPLIER_PRO_PROCESS_EQUIPMENT empObj = new SUPPLIER_PRO_PROCESS_EQUIPMENT(); empObj.SupplierCode = entity.SupplierCode; empObj.SupplierName = entity.SupplierName; empObj.CheryProductNo = entity.CheryProductNo; empObj.CheryProductName = entity.CheryProductName; empObj.VendorProductNo = entity.VendorProductNo; empObj.VendorProductName = entity.VendorProductName; empObj.DeviceType = entity.DeviceType; empObj.DeviceCode = entity.DeviceCode; empObj.DeviceName = entity.DeviceName; empObj.Manufacturer = entity.Manufacturer; empObj.ModelNumber = entity.ModelNumber; empObj.SerialNumber = entity.SerialNumber; empObj.ProductionDate = entity.ProductionDate; empObj.Material = entity.Material; empObj.CurrentLocation = entity.CurrentLocation; empObj.DeviceStatus = entity.DeviceStatus; empObj.CavityCount = entity.CavityCount; empObj.MoldSize = entity.MoldSize; empObj.DesignLifeUnits = entity.DesignLifeUnits; empObj.DesignLifeValue = entity.DesignLifeValue; empObj.CurrentUsageCount = entity.CurrentUsageCount; empObj.OverhaulCount = entity.OverhaulCount; empObj.CoolingChannelLayout = entity.CoolingChannelLayout; empObj.DetectionAccuracy = entity.DetectionAccuracy; empObj.CalibrationDate = entity.CalibrationDate; empObj.CalibrationDueDays = entity.CalibrationDueDays; empObj.ToleranceRange = entity.ToleranceRange; empObj.WearThreshold = entity.WearThreshold; empObj.DetectionRange = entity.DetectionRange; empObj.UnitType = entity.UnitType; empObj.SupplierCode = VendCode; empObj.TaskId = taskSubObj.TaskId; empObj.ReadState = true; await _context.AddAsync(empObj); //await _supplierProProcessEquipmentRepository.AddAsync(empObj); //_context.BulkMerge(new List { entity }, //itm => itm.SupplierCode, //itm => itm.CheryProductNo, //itm => itm.DeviceCode, //itm => itm.DeviceType // ); var firstObj = _context.Set().FirstOrDefault( itm => itm.SupplierCode == entity.SupplierCode && itm.CheryProductNo == entity.CheryProductNo && itm.DeviceCode == entity.DeviceCode && itm.DeviceType == entity.DeviceType ); if (firstObj == null) { throw new Exception("数据库不存在,不能更新"); } else { var ret = await base.Update(entity); } _context.SaveChanges(); //await _context.BulkMergeAsync(new List { entity }, options => //{ // options.ColumnPrimaryKeyExpression = itm => //new { itm.SupplierCode, itm.CheryProductNo, itm.DeviceCode, itm.DeviceType }; options.Transaction = tran; //} //); //SUPPLIER_PRO_PROCESS_EQUIPMENT empObj = EntityMapper.Trans(entity); //empObj.TaskId = taskSubObj.TaskId; //await _supplierProProcessEquipmentRepository.AddAsync(empObj); //var firstObj = _context.Set().FirstOrDefault( // itm => itm.SupplierCode == entity.SupplierCode // && itm.CheryProductNo == entity.CheryProductNo // && itm.DeviceCode == entity.DeviceCode // && itm.DeviceType == entity.DeviceType // ); //if (firstObj == null) //{ // throw new Exception("数据库不存在,不能更新"); //} //else //{ // var ret = await base.Update(entity); //} #endregion transaction.Commit(); return Ok(true); } catch (Exception ex) { transaction.Rollback(); throw new Exception("方法体执行报错,事务回滚:" + ex.Message); } } } }