Exemplo n.º 1
0
        public CommonResponse <UserVM> SaveNewData(UserVM data, TableTransactionVM transaction)
        {
            CommonResponse <UserVM> result;

            using Microsoft.EntityFrameworkCore.Storage.IDbContextTransaction dbTransaction = DbContext.Database.BeginTransaction();

            try
            {
                string transactionId = TransactionRepository.InitializeTransaction(transaction);

                result = UserRepository.SaveData(data, transactionId);

                dbTransaction.Commit();
            }
            catch (Exception e)
            {
                dbTransaction.Rollback();

                Logger.LogError("Error Saving User Data by IP Address {0} : {1}\nInner Ex : {2}",
                                transaction?.IpAddress ?? "",
                                e.Message ?? "",
                                e.InnerException?.Message ?? ""
                                );

                result = new CommonResponse <UserVM>
                {
                    Status  = false,
                    Code    = "E-003",
                    Message = "Save Data Failed! Please Contact an Web Administrator!",
                    Data    = new UserVM[] { data },
                };
            }

            return(result);
        }
        public async Task <IActionResult> OnPostAsync(Guid?id)
        {
            if (id == null)
            {
                return(NotFound());
            }

            Project = await db.Project.FindAsync(id);

            if (Project != null)
            {
                using (Microsoft.EntityFrameworkCore.Storage.IDbContextTransaction transaction = db.Database.BeginTransaction())
                {
                    try
                    {
                        db.ProjectFeature.RemoveRange(db.ProjectFeature.Where(w => w.ProjectId == Project.Id));
                        db.Project.Remove(Project);
                        await db.SaveChangesAsync();

                        transaction.Commit();
                    }
                    catch (Exception)
                    {
                        transaction.Rollback();
                        throw;
                    }
                }
            }

            return(RedirectToPage("./Index"));
        }
Exemplo n.º 3
0
        public FuncResult Bind(List <SysUserDataCondition> model, string currentUserId)
        {
            //检查是否重复绑定
            foreach (SysUserDataCondition obj in model)
            {
                SysUserDataCondition entity = _context.SysUserDataCondition.
                                              FirstOrDefault(e => ((!string.IsNullOrWhiteSpace(obj.UserGroupId) && e.UserGroupId == obj.UserGroupId) || (e.UserId == obj.UserId)) &&
                                                             e.ConditionId == obj.ConditionId && e.ConditionValue == obj.ConditionValue &&
                                                             e.ControllerId == obj.ControllerId);
                if (entity != null)
                {
                    return(new FuncResult()
                    {
                        IsSuccess = false, Message = $"[{obj.ConditionValue}] 已经绑定请勿重复操作!"
                    });
                }

                entity = new SysUserDataCondition()
                {
                    Id             = Guid.NewGuid().ToString("N"),
                    UserId         = obj.UserId,
                    UserGroupId    = obj.UserGroupId,
                    ConditionName  = obj.ConditionName,
                    ConditionId    = obj.ConditionId,
                    ConditionValue = obj.ConditionValue,
                    ControllerId   = obj.ControllerId,
                    SortValue      = obj.SortValue,

                    CreatedBy      = currentUserId,
                    CreationDate   = DateTime.Now,
                    LastUpdatedBy  = currentUserId,
                    LastUpdateDate = DateTime.Now
                };
                _context.SysUserDataCondition.Add(entity);
            }

            using (Microsoft.EntityFrameworkCore.Storage.IDbContextTransaction trans = _context.Database.BeginTransaction())
            {
                try
                {
                    _context.SaveChanges();
                    trans.Commit();
                }
                catch (Exception ex)
                {
                    LogService.WriteError(ex);
                    trans.Rollback();
                    return(new FuncResult()
                    {
                        IsSuccess = false, Message = "添加数据时发生了预料之外的错误,请稍后重试"
                    });
                }
            }
            return(new FuncResult()
            {
                IsSuccess = true
            });
        }
Exemplo n.º 4
0
        public async Task <FuncResult> Add(DataConditionModel model, string currentUserId)
        {
            if (_context.SysDataCondition.FirstOrDefault(e => e.TableName.ToUpper() == model.TableName.ToUpper()) != null)
            {
                return(new FuncResult()
                {
                    IsSuccess = false, Message = "数据维度表名不能重复"
                });
            }

            SysDataCondition entity = new SysDataCondition
            {
                SysDataConditionId = Guid.NewGuid().ToString("N"),
                ConditionName      = model.ConditionName,
                ParentId           = model.ParentId,
                SortValue          = model.SortValue,
                ConditionDesc      = model.ConditionDesc,
                ConditionValue     = model.ConditionValue,

                TableName          = model.TableName,
                ParentColumn       = model.ParentColumn,
                ConditionValueDesc = model.ConditionValueDesc,
                ChildColumn        = model.ChildColumn,
                MasterSlaveFlag    = model.MasterSlaveFlag == true?1:0,

                CreationDate   = DateTime.Now,
                CreatedBy      = currentUserId,
                LastUpdateDate = DateTime.Now,
                LastUpdatedBy  = currentUserId
            };
            await _context.SysDataCondition.AddAsync(entity);

            using (Microsoft.EntityFrameworkCore.Storage.IDbContextTransaction trans = _context.Database.BeginTransaction())
            {
                try
                {
                    await _context.SaveChangesAsync();

                    trans.Commit();
                    return(new FuncResult()
                    {
                        IsSuccess = true, Content = entity, Message = "添加成功"
                    });
                }
                catch (Exception ex)
                {
                    trans.Rollback();
                    return(new FuncResult()
                    {
                        IsSuccess = false, Content = ex.Message, Message = "添加失败"
                    });
                }
            }
        }
Exemplo n.º 5
0
        public async Task <FuncResult> Add(SysModelInfo model, string currentUserId)
        {
            //模块名称不能重复
            if (_context.SysModelInfo.FirstOrDefault(e => e.ModelName == model.ModelName) != null)
            {
                return(new FuncResult()
                {
                    IsSuccess = false, Message = "模块名不能重复!"
                });
            }
            if (string.IsNullOrWhiteSpace(model.ModelGroupId))
            {
                return(new FuncResult()
                {
                    IsSuccess = false, Message = "所属模块组不能为空"
                });
            }

            model.ModelId        = Guid.NewGuid().ToString();
            model.LastUpdatedBy  = currentUserId;
            model.LastUpdateDate = DateTime.Now;
            model.CreatedBy      = currentUserId;
            model.CreationDate   = DateTime.Now;
            model.DeleteFlag     = 0;
            await _context.SysModelInfo.AddAsync(model);

            using (Microsoft.EntityFrameworkCore.Storage.IDbContextTransaction trans = _context.Database.BeginTransaction())
            {
                try
                {
                    await _context.SaveChangesAsync();

                    trans.Commit();
                }
                catch (Exception ex)
                {
                    trans.Rollback();
                    return(new FuncResult()
                    {
                        IsSuccess = false, Message = ex.Message
                    });
                }
            }
            return(new FuncResult()
            {
                IsSuccess = true, Content = model, Message = "添加成功"
            });
        }
        public async Task <FuncResult> Add(SysUserInfoModel model, int currentUserId)
        {
            SysUserInfo entity = new SysUserInfo
            {
                User_Account     = model.UserAccount,
                User_Name        = model.UserName,
                User_Password    = model.UserPassword,
                User_Org_Id      = model.UserOrgId,
                User_Group_Names = model.UserGroupNames,
                User_Email       = model.UserEmail,
                User_Is_Ldap     = model.UserIsLdap,
                User_Mobile_No   = model.UserMobileNo,
                User_Ower        = model.UserOwer,
                Language_Code    = model.LanguageCode,
                User_Is_Lock     = model.UserIsLock,
                Eff_Start_Date   = model.EffStartDate,
                Eff_End_Date     = model.EffEndDate,

                Creation_Date = DateTime.Now,
                Created_By    = currentUserId
            };
            await _context.SysUserInfos.AddAsync(entity);

            using (Microsoft.EntityFrameworkCore.Storage.IDbContextTransaction trans = _context.Database.BeginTransaction())
            {
                try
                {
                    await _context.SaveChangesAsync();

                    trans.Commit();
                }
                catch (Exception ex)
                {
                    trans.Rollback();
                    return(new FuncResult()
                    {
                        IsSuccess = false, Content = ex.Message
                    });
                }
            }


            return(new FuncResult()
            {
                IsSuccess = true, Content = entity, Message = "添加成功"
            });
        }
        public async Task <FuncResult> Add(SysModelGroupModel model, int currentUserId)
        {
            var entity = new SysModelGroup()
            {
                Model_Group_Code = model.ModelGroupCode,
                Model_Group_Name = model.ModelGroupName,
                Parent_Id        = model.ParentId,
                Sort_Flag        = model.SortFlag,
                Enable_Flag      = model.EnableFlag,
                Image_Url        = model.ImageUrl,
                Group_Belong     = model.GroupBelong,
                Biz_Sys_Code     = model.BizSysCode,

                Last_Updated_By  = currentUserId,
                Last_Update_Date = DateTime.Now,

                Created_By    = currentUserId,
                Creation_Date = DateTime.Now
            };
            await _context.SysModelGroups.AddAsync(entity);

            using (Microsoft.EntityFrameworkCore.Storage.IDbContextTransaction trans = _context.Database.BeginTransaction())
            {
                try
                {
                    await _context.SaveChangesAsync();

                    trans.Commit();
                }
                catch (Exception ex)
                {
                    trans.Rollback();
                    return(new FuncResult()
                    {
                        IsSuccess = false, Content = ex.Message
                    });
                }
            }
            return(new FuncResult()
            {
                IsSuccess = true, Content = entity, Message = "添加成功"
            });
        }
Exemplo n.º 8
0
 private void saveDBBtn_Click(object sender, EventArgs e)//+
 {
     try
     {
         using (profileContext db = new profileContext())
         {
             using (Microsoft.EntityFrameworkCore.Storage.IDbContextTransaction tr = db.Database.BeginTransaction())
             {
                 try
                 {
                     try
                     {
                         DataManipulationService.SaveProfileToDB(db, tr, Document);
                         tr.Commit();
                     }
                     catch (Exception ex)
                     {
                         tr.Rollback();
                         MessageBox.Show(ex.Message);
                         return;
                     }
                     DataManipulationService.SaveResultToDB(db, tr, Document);
                 }
                 catch (Exception ex)
                 {
                     MainProfile mainProfile = db.MainProfile.SingleOrDefault(p => p.Name == Document.DocumentName);
                     if (mainProfile != null)
                     {
                         db.MainProfile.Remove(mainProfile);
                         db.SaveChanges();
                     }
                     MessageBox.Show(ex.Message);
                     return;
                 }
             }
         }
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message);
     }
 }
        public async Task <IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                ViewData["ClientId"] = new SelectList(db.Client, "Id", "Code");
                return(Page());
            }


            using (Microsoft.EntityFrameworkCore.Storage.IDbContextTransaction transaction = db.Database.BeginTransaction())
            {
                try
                {
                    var projectFeatureResult = await new ProjectService().UploadProjectFeaturesAsync(UploadFeatureFile, Project.Id);

                    // Perform a second check to catch ProcessFormFile method
                    // violations.
                    if (!projectFeatureResult.ModelState.IsValid)
                    {
                        ViewData["ClientId"] = new SelectList(db.Client, "Id", "Code");
                        return(Page());
                    }

                    db.ProjectFeature.AddRange(projectFeatureResult.ProjectFeatures);
                    db.Project.Add(Project);

                    await db.SaveChangesAsync();

                    transaction.Commit();

                    return(RedirectToPage("./Index"));
                }

                catch (Exception)
                {
                    transaction.Rollback();

                    throw;
                }
            }
        }
Exemplo n.º 10
0
        public async Task <FuncResult> Delete(string[] ids, int currentuserId)
        {
            var entitys = _context.SysModules.Where(e => ids.Contains(e.Id));

            if (entitys.Count() != ids.Length)
            {
                return(new FuncResult()
                {
                    IsSuccess = false, Message = "参数错误"
                });
            }
            foreach (var obj in entitys)
            {
                obj.Delete_By   = currentuserId;
                obj.Delete_Flag = true;
                obj.Delete_Time = DateTime.Now;
                _context.SysModules.Update(obj);
            }
            using (Microsoft.EntityFrameworkCore.Storage.IDbContextTransaction trans = _context.Database.BeginTransaction())
            {
                try
                {
                    await _context.SaveChangesAsync();

                    trans.Commit();
                }
                catch (Exception ex)
                {
                    trans.Rollback();
                    LogService.WriteError(ex);
                    return(new FuncResult()
                    {
                        IsSuccess = false, Message = "删除时发生了意料之外的错误"
                    });
                }
            }
            return(new FuncResult()
            {
                IsSuccess = true, Message = $"已成功删除{ids.Length}条记录"
            });
        }
Exemplo n.º 11
0
 public void PlaceOrder(Models.Order order)
 {
     Entities.StoreOrder o = new Entities.StoreOrder();
     if (order.Location.LocationID != null)
     {
         o.LocationId = (int)order.Location.LocationID;
     }
     if (order.Customer.CustomerID != null)
     {
         o.CustomerId = (int)order.Customer.CustomerID;
     }
     o.CheckedOut = DateTime.Now;
     ctx.StoreOrders.Add(o);
     foreach (Models.Item i in order.Items)
     {
         Entities.OrderItem oi = new Entities.OrderItem();
         if (i.Product.ProductID != null)
         {
             oi.ProductId = (int)i.Product.ProductID;
         }
         oi.Quantity = i.Quantity;
         o.OrderItems.Add(oi);
     }
     ctx.SaveChanges();
     try {
         transaction.Commit();
         using var log = new LoggerConfiguration()
                         .WriteTo.File("log.txt", rollingInterval: RollingInterval.Day, shared: true)
                         .CreateLogger();
         log.Information("TRANSACTION: Committed");
         transaction.Dispose();
         transaction = ctx.Database.BeginTransaction();
     } catch (Exception e) {
         Console.WriteLine(e.StackTrace);
         using var log = new LoggerConfiguration()
                         .WriteTo.File("log.txt", rollingInterval: RollingInterval.Day, shared: true)
                         .CreateLogger();
         log.Information("TRANSACTION: Rolled back due to database throwing exception");
         transaction.Rollback();
     }
 }
Exemplo n.º 12
0
        public async Task <FuncResult> Delete(string[] ids, string currentUserId)
        {
            IQueryable <ApdFctTAx> entitys = _context.ApdFctTAx.Where(e => ids.Contains(e.RECORD_ID));

            if (entitys.Count() != ids.Length)
            {
                return(new FuncResult()
                {
                    IsSuccess = false, Message = "参数错误"
                });
            }
            foreach (ApdFctTAx obj in entitys)
            {
                //删除
                _context.ApdFctTAx.Remove(obj);
            }
            using (Microsoft.EntityFrameworkCore.Storage.IDbContextTransaction trans = _context.Database.BeginTransaction())
            {
                try
                {
                    await _context.SaveChangesAsync();

                    trans.Commit();
                }
                catch (Exception ex)
                {
                    trans.Rollback();
                    LogService.WriteError(ex);
                    return(new FuncResult()
                    {
                        IsSuccess = false, Message = "删除时发生了意料之外的错误"
                    });
                }
            }
            return(new FuncResult()
            {
                IsSuccess = true, Message = $"已成功删除{ids.Length}条记录"
            });
        }
Exemplo n.º 13
0
        public async Task <IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                return(Page());
            }

            Project.ModifiedDate = DateTime.UtcNow;
            Project.ModifiedBy   = User.Identity.Name;

            db.Attach(Project).State = EntityState.Modified;

            using (Microsoft.EntityFrameworkCore.Storage.IDbContextTransaction transaction = db.Database.BeginTransaction())
            {
                try
                {
                    await db.SaveChangesAsync();

                    transaction.Commit();

                    return(RedirectToPage("./Index"));
                }
                catch (DbUpdateConcurrencyException)
                {
                    transaction.Rollback();

                    if (!ProjectExists(Project.Id))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
            }
        }
Exemplo n.º 14
0
        public async Task <FuncResult> Add(SysModuleModel model, int currentUserId)
        {
            //模块名称不能重复
            if (_context.SysModules.FirstOrDefault(e => e.ModuleName == model.ModuleName) != null)
            {
                return(new FuncResult()
                {
                    IsSuccess = false, Message = "模块名不能重复!"
                });
            }
            int level = 1;

            if (!string.IsNullOrWhiteSpace(model.ParentId))
            {
                var parent_entity = _context.SysModules.FirstOrDefault(e => e.Id == model.ParentId);
                if (parent_entity == null)
                {
                    return(new FuncResult()
                    {
                        IsSuccess = false, Message = "父级ID错误"
                    });
                }
                level = parent_entity.Level + 1;
            }

            var entity = new SysModule()
            {
                ModuleName = model.ModuleName,
                Level      = level,
                ParentId   = model.ParentId,


                Last_Updated_By  = currentUserId,
                Last_Update_Date = DateTime.Now,

                Created_By    = currentUserId,
                Creation_Date = DateTime.Now
            };
            await _context.SysModules.AddAsync(entity);

            using (Microsoft.EntityFrameworkCore.Storage.IDbContextTransaction trans = _context.Database.BeginTransaction())
            {
                try
                {
                    await _context.SaveChangesAsync();

                    trans.Commit();
                }
                catch (Exception ex)
                {
                    trans.Rollback();
                    return(new FuncResult()
                    {
                        IsSuccess = false, Content = ex.Message
                    });
                }
            }
            return(new FuncResult()
            {
                IsSuccess = true, Content = entity, Message = "添加成功"
            });
        }
Exemplo n.º 15
0
        public ActionResult CrearEditarTraslado(TrasladoViewModel traslado, IList<TrasladoInventarioViewModel> inventarioTraslado, IList<long> eliminados)
        {

            TrasladoInventarioRepository rep = new TrasladoInventarioRepository(context);
            TbPrTraslado original = trasladoService.GetTrasladoById(traslado.IdTraslado); //adquiere todos los hijos asociados
            TbPrTraslado tr;
            Microsoft.EntityFrameworkCore.Storage.IDbContextTransaction trans = context.Database.BeginTransaction();
            using (trans)
            {

                try
                {
                    if (traslado.Comentario == null)
                    {
                        traslado.Comentario = "";
                    }

                    if (traslado.IdTraslado != 0)
                    {

                       
                        tr =  trasladoService.GetTrasladoById(traslado.IdTraslado);

                        if (inventarioTraslado.Count() > 0)//nuevas y editadas
                        {

                            foreach (var item in inventarioTraslado)

                            {
                                if (item.Id == 0)
                                {
                                    tr.TbPrTrasladoInventario.Add(trasladoInventarioMap.ViewModelToDomain(item));//adquiere los hijos
                                }
                                else
                                {
                                    tr.TbPrTrasladoInventario.FirstOrDefault(d => d.Id == item.Id).Id = item.Id;
                                    tr.TbPrTrasladoInventario.FirstOrDefault(d => d.Id == item.Id).IdTraslado = item.IdTraslado;
                                    tr.TbPrTrasladoInventario.FirstOrDefault(d => d.Id == item.Id).IdInventario = item.IdInventario;
                                    tr.TbPrTrasladoInventario.FirstOrDefault(d => d.Id == item.Id).CodigoArticulo = item.CodigoArticulo;
                                    tr.TbPrTrasladoInventario.FirstOrDefault(d => d.Id == item.Id).Descripcion = item.Descripcion;
                                    tr.TbPrTrasladoInventario.FirstOrDefault(d => d.Id == item.Id).Cantidad = item.Cantidad;
                                    tr.TbPrTrasladoInventario.FirstOrDefault(d => d.Id == item.Id).PrecioUnitario = item.PrecioUnitario;
                                    tr.TbPrTrasladoInventario.FirstOrDefault(d => d.Id == item.Id).CostoTotal = item.CostoTotal;

                                }
                            }
                        }
                      
                        if (eliminados.Count() > 0)
                        {
                            var borrar = new List<TbPrTrasladoInventario>();
                            foreach (var item in eliminados)
                            {
                                borrar.Add(tr.TbPrTrasladoInventario.Where(f => f.Id == item).ElementAt(0));
                                tr.TbPrTrasladoInventario.Remove(tr.TbPrTrasladoInventario.Where(f => f.Id == item).ElementAt(0));
                            }
                            context.RemoveRange(borrar);
                            context.SaveChanges();
                        }
                        tr.Comentario = traslado.Comentario;
                        tr.CostoTraslado = traslado.CostoTraslado;
                        tr.Fecha = traslado.Fecha;
                        tr.Anulado = traslado.Anulado;
                        context.Update(tr);
                      
                        kardexMap.CreateKardexTRI(tr,original, eliminados);
                        context.SaveChanges();

                    }
                    else
                    {
                        traslado.TrasladoInventarioDetalle = inventarioTraslado;
                        traslado.IdUsuario = int.Parse(User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier)?.Value); //adquiere el id del usuario en session
                        traslado.FechaCreacion = DateTime.Now; //adquiere la fecha
                        traslado.Anulado = false;//por defecto false

                        tr = trasladoMap.ViewModelToDomain(traslado);//obtiene al padre

                        foreach (var item in inventarioTraslado)
                        {
                            tr.TbPrTrasladoInventario.Add(trasladoInventarioMap.ViewModelToDomain(item));//adquiere los hijos
                        }

                        context.Add(tr);
                        context.SaveChanges();
                        kardexMap.CreateKardexTRI(tr, original, eliminados);//inserta en el kardex

                    }
                    trans.Commit();
                    return Json(new { success = true });
                }
                catch (Exception ex)
                {
                    trans.Rollback();
                    AltivaLog.Log.Insertar(ex.ToString(), "Error");

                    if (ex.HResult.ToString() == "-2146233088")
                    {                       
                        return BadRequest(new { rollback = true });
                    }
                    else
                    {
                        return BadRequest(new { rollback = false });
                    }

                }

            }

        }
Exemplo n.º 16
0
 public void Rollback()
 {
     transaction.Rollback();
     Dispose();
 }
Exemplo n.º 17
0
        /// <summary>
        /// 账户至少6位,密码需要复杂度检测
        /// </summary>
        /// <param name="model"></param>
        /// <param name="currentUserId"></param>
        /// <returns></returns>
        public async Task <FuncResult> Add(SysUserInfoModel model, string currentUserId)
        {
            SysUserInfo entity = new SysUserInfo
            {
                UserId       = Guid.NewGuid().ToString(),
                UserAccount  = model.UserAccount,
                UserName     = model.UserName,
                UserPassword = model.UserPassword,
                // UserOrgId = model.UserOrgId,
                UserGroupNames = model.UserGroupNames,
                UserEmail      = model.UserEmail,
                UserMobile     = model.UserMobileNo,
                //LanguageCode = model.LanguageCode,
                LastUpdatedBy  = currentUserId,
                LastUpdateDate = DateTime.Now,
                CreationDate   = DateTime.Now,
                CreatedBy      = currentUserId,
                ValidTime      = model.UserValidTime
            };

            if (entity.UserAccount.Length < 6)
            {
                return(new FuncResult()
                {
                    IsSuccess = false, Message = "账户至少设置6位!"
                });
            }

            var pr = passwordverify(entity.UserPassword);

            if (pr != Strength.Normal)
            {
                if (pr == Strength.Invalid)
                {
                    return(new FuncResult()
                    {
                        IsSuccess = false, Message = "密码至少8位!"
                    });
                }
                return(new FuncResult()
                {
                    IsSuccess = false, Message = "密码至少8位,由数字、字母或特殊字符中2种方式组成!"
                });
            }

            await _context.SysUserInfo.AddAsync(entity);

            using (Microsoft.EntityFrameworkCore.Storage.IDbContextTransaction trans = _context.Database.BeginTransaction())
            {
                try
                {
                    await _context.SaveChangesAsync();

                    trans.Commit();
                }
                catch (Exception ex)
                {
                    trans.Rollback();
                    return(new FuncResult()
                    {
                        IsSuccess = false, Content = ex.Message
                    });
                }
            }


            return(new FuncResult()
            {
                IsSuccess = true, Content = entity, Message = "添加成功"
            });
        }
        public async Task <FuncResult> Add(DimStoreModel model, int currentUserId)
        {
            if (_context.DimStore.Count(e => e.stCode == model.stCode) > 0)
            {
                return(new FuncResult()
                {
                    IsSuccess = false, Message = "已经存在相同的店铺编码。"
                });
            }
            DimStore entity = new DimStore
            {
                stCode       = model.stCode,
                stRegion     = model.stRegion,
                stCity       = model.stCity,
                stLocation   = model.stLocation,
                stBrand      = model.stBrand,
                stOM         = model.stOM,
                stDM         = model.stDM,
                stName       = model.stName,
                stName_en    = model.stName_en,
                stAddress    = model.stAddress,
                stAddress_en = model.stAddress_en,
                stType       = model.stType,
                stOpenDate   = model.stOpenDate,
                stCloseDate  = model.stCloseDate,
                stTel        = model.stTel,
                stFax        = model.stFax,
                stEmail      = model.stEmail,
                stIP         = model.stIP,
                stSpace      = model.stSpace,
                stSeat       = model.stSeat,
                stBizTime    = model.stBizTime,
                stPOST       = model.stPOST,
                stSM         = model.stSM,
                stSMTel      = model.stSMTel,
                stComments   = model.stComments,

                Creation_Date = DateTime.Now,
                Created_By    = currentUserId
            };
            await _context.DimStore.AddAsync(entity);

            using (Microsoft.EntityFrameworkCore.Storage.IDbContextTransaction trans = _context.Database.BeginTransaction())
            {
                try
                {
                    await _context.SaveChangesAsync();

                    trans.Commit();
                }
                catch (Exception ex)
                {
                    trans.Rollback();
                    return(new FuncResult()
                    {
                        IsSuccess = false, Content = ex.Message
                    });
                }
            }


            return(new FuncResult()
            {
                IsSuccess = true, Content = entity, Message = "添加成功"
            });
        }
Exemplo n.º 19
0
        public Task <OrderPenjualan> UpdateOrder(int id, OrderPenjualan order)
        {
            Microsoft.EntityFrameworkCore.Storage.IDbContextTransaction trans = dbContext.Database.BeginTransaction();
            try
            {
                //    dbContext.ChangeTracker.Clear();
                ValidateCreateOrder(order);
                var lastOrder = dbContext.OrderPenjualan.Where(x => x.Id == id)
                                .Include(x => x.Gudang)
                                .Include(x => x.Customer)
                                .Include(x => x.Sales)
                                .Include(x => x.Items).FirstOrDefault();

                if (lastOrder == null)
                {
                    throw new SystemException("Order Not Found  !");
                }


                if (lastOrder.Customer.Id != order.Customer.Id)
                {
                    lastOrder.Customer = order.Customer;
                }

                if (lastOrder.Sales.Id != order.Sales.Id)
                {
                    lastOrder.Sales = order.Sales;
                }

                if (lastOrder.Gudang.Id != order.Gudang.Id)
                {
                    lastOrder.Gudang = order.Gudang;
                }
                lastOrder.DeadLine = order.DeadLine;

                foreach (var item in order.Items)
                {
                    if (item.Id <= 0)
                    {
                        dbContext.Entry(item.Product).State = EntityState.Detached;
                        dbContext.Entry(item.Unit).State    = EntityState.Detached;
                        dbContext.OrderPenjualanItem.Add(item);
                    }
                    else
                    {
                        var olditem = lastOrder.Items.Where(x => x.Id == item.Id).FirstOrDefault();
                        if (olditem != null)
                        {
                            if (olditem.Product != null)
                            {
                                dbContext.Entry(olditem.Product).State = EntityState.Unchanged;
                            }
                            if (olditem.Unit != null)
                            {
                                dbContext.Entry(olditem.Unit).State = EntityState.Unchanged;
                            }
                            dbContext.Entry <OrderPenjualanItem>(olditem).CurrentValues.SetValues(item);
                        }
                    }
                }

                dbContext.Entry <OrderPenjualan>(lastOrder).CurrentValues.SetValues(order);
                foreach (var item in lastOrder.Items)
                {
                    var existsDb = order.Items.Where(x => x.Id == item.Id).FirstOrDefault();
                    if (existsDb == null)
                    {
                        lastOrder.Items.Remove(item);
                    }
                }
                var result = dbContext.SaveChanges();
                trans.Commit();
                return(Task.FromResult(order));
            }
            catch (Exception ex)
            {
                trans.Rollback();
                throw new SystemException(ex.Message);
            }
        }