예제 #1
0
        /// <inheritdoc />
        public Result UpdateOrder(OrderDto orderDto)
        {
            using var transaction = _context.Database.BeginTransaction();
            try
            {
                var customer         = _context.Customers.Find(orderDto.CustomerId);
                var productsQueryNew =
                    _context.Products.Where(x => orderDto.ProductsId.Contains(x.Id)).ToList();
                var order = _context.Orders.Include(x => x.Products).FirstOrDefault(x => x.Id == orderDto.Id);

                if (order != null)
                {
                    order.Customer   = customer ?? null;
                    order.Sum        = orderDto.Sum;
                    order.TimeAdd    = orderDto.TimeAdd;
                    order.TimeUpdate = orderDto.TimeUpdate;

                    _context.Update(order);
                    _context.SaveChanges();

                    if (productsQueryNew.Count > 0)
                    {
                        var oldProduct = order.Products;
                        if (oldProduct.Count > 0)
                        {
                            _context.RemoveRange(oldProduct);
                        }

                        var products = productsQueryNew.Select(x => new OrderProduct
                        {
                            OrderId = order.Id, Order = order, Product = x, ProductId = x.Id
                        });

                        _context.AddRange(products);
                        _context.SaveChanges();
                    }

                    transaction.Commit();
                    return(Result.Ok());
                }

                return(Result.Fail("Обновление не увенчалось успехом."));
            }
            catch (Exception e)
            {
                transaction.Rollback();
                throw new ApplicationException(e.InnerException.Message ?? e.Message);
            }
        }