public void EditProduct(int id, ProductDTO product)
        {
            var DbProduct = _context.Products.First(p => p.Id == product.Id);

            if (id == DbProduct.Id)
            {
                DbProduct.Name  = product.Name;
                DbProduct.Price = product.Price;
            }
            else
            {
                _context.Products.Add(new Product
                {
                    Name     = product.Name,
                    ImageUrl = product.ImageUrl,
                    Order    = product.Order,
                    Price    = product.Price,
                    Brand    = new Brand
                    {
                        Id   = product.Brand.Id,
                        Name = product.Brand.Name
                    }
                });
            }

            _context.SaveChanges();
        }
Пример #2
0
        public OrderDTO CreateOrder(CreateOrderModel OrderModel, string UserName)
        {
            var user = _userManager
                       .FindByNameAsync(UserName)
                       .Result;

            using (var trans = _context.Database.BeginTransaction())
            {
                var order = new Order()
                {
                    Name    = OrderModel.OrderViewModel.Name,
                    Address = OrderModel.OrderViewModel.Address,
                    Date    = DateTime.Now,
                    Phone   = OrderModel.OrderViewModel.Phone,
                    User    = user
                };

                _context.Orders.Add(order);

                foreach (var item in OrderModel.OrderItems)
                {
                    //var productVm = item.Id;

                    var product = _context.Products.FirstOrDefault(p => p.Id == item.Id);

                    if (product == null)
                    {
                        throw new InvalidOperationException($"Товар с id:{item.Id} не найден в БД");
                    }

                    var orderItem = new OrderItem()
                    {
                        Order    = order,
                        Product  = product,
                        Price    = product.Price,
                        Quantity = item.Quantity
                    };

                    _context.OrderItems.Add(orderItem);
                }

                _context.SaveChanges();
                trans.Commit();

                _Logger.LogInformation("Заказ для пользователя {0} создан успешно, номер заказа {1}", user.UserName, order.Id);

                return(order.ToDTO());
            }
        }