public async Task <OrderDTO> CreateOrder(string UserName, CreateOrderModel OrderModel)
        {
            var user = await _UserManager.FindByNameAsync(UserName);

            if (user is null)
            {
                throw new InvalidOperationException($"Пользователь {UserName} не найден в БД");
            }

            await using var transaction = await _Db.Database.BeginTransactionAsync();

            var order = new Order
            {
                Name   = OrderModel.Order.Name,
                Adress = OrderModel.Order.Address,
                Phone  = OrderModel.Order.Phone,
                User   = user,
                Date   = DateTime.Now,
            };

            foreach (var(id, _, quantity) in OrderModel.Items)
            {
                var product = await _Db.Products.FindAsync(id);

                if (product is null)
                {
                    continue;
                }

                var order_item = new OrderItem
                {
                    Order    = order,
                    Price    = product.Price,
                    Quantity = quantity,
                    Product  = product,
                };
                order.Items.Add(order_item);
            }

            await _Db.AddAsync(order);

            await _Db.SaveChangesAsync();

            await transaction.CommitAsync();

            return(order.ToDTO());
        }
예제 #2
0
        public async Task <Order> CreateOrderAsync(string Username, CartViewModel cart, OrderViewModel orderModel)
        {
            var user = await userManager.FindByNameAsync(Username);

            using (var transaction = await db.Database.BeginTransactionAsync())
            {
                var order = new Order
                {
                    Name    = orderModel.Name,
                    Address = orderModel.Address,
                    Phone   = orderModel.Phone,
                    User    = user,
                    Date    = DateTime.Now
                };

                await db.AddAsync(order);

                foreach (var(productModel, quantity) in cart.Items)
                {
                    var product = await db.Products.FirstOrDefaultAsync(x => x.Id == productModel.Id);

                    if (product is null)
                    {
                        throw new InvalidOperationException($"Товар с Id: {productModel.Id} в базе данных не найден!");
                    }

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

                    await db.OrderItems.AddAsync(orderItem);
                }

                await db.SaveChangesAsync();

                await transaction.CommitAsync();

                return(order);
            }
        }