예제 #1
0
        public bool ProcessOrder(AddressModel address, ContactModel contact, ShoppingCartModel cart, int paymentId, int deliveryId, string comment)
        {
            var dbAddress      = GetAddressByStreet(address);
            var dbContact      = GetContactBySocialSecurityNumber(dbAddress, contact);
            var dbPaymentType  = GetPaymentTypeById(paymentId);
            var dbDeliveryType = GetDeliveryTypeById(deliveryId);

            using (var transaction = context.Database.BeginTransaction())
            {
                try
                {
                    var order = new Order
                    {
                        Address      = dbContact.Address,
                        Contact      = dbContact,
                        OrderNumber  = System.Guid.NewGuid().ToString(),
                        DeliveryType = dbDeliveryType,
                        PaymentType  = dbPaymentType,
                        TotalPrice   = cart.GetCartTotal(),
                        OrderDate    = DateTime.Now,
                        Comment      = comment,
                    };
                    context.Orders.Add(order);
                    context.SaveChanges();

                    foreach (var item in cart.Items)
                    {
                        if (item.Quantity <= item.Book.QuantityInStock)
                        {
                            var orderDetail = new OrderDetail
                            {
                                OrderId         = order.Id,
                                Book            = GetBookById(item.Book.Id),
                                QuantityOrdered = item.Quantity,
                            };
                            context.OrderDetails.Add(orderDetail);
                            var bookBought = context.Books.Find(item.Book.Id);
                            bookBought.QuantityInStock -= item.Quantity;
                        }
                        else
                        {
                            transaction.Rollback();
                            return(false);
                        }
                    }
                    context.SaveChanges();
                    transaction.Commit();
                    return(true);
                }

                catch (Exception E)
                {
                }
            }
            return(true);
        }