コード例 #1
0
        public OrderRecord CreateOrder(int customerId, IEnumerable <ShoppingCartItem> items)
        {
            if (items == null)
            {
                throw new ArgumentNullException("items");
            }

            // Convert to an array to avoid re-running the enumerable
            var itemsArray = items.ToArray();

            if (!itemsArray.Any())
            {
                throw new ArgumentException("Creating an order with 0 items is not supported", "items");
            }

            var order = new OrderRecord {
                CreatedAt  = _dateTimeService.Now,
                CustomerId = customerId,
                Status     = "New",
                //SubTotal   = 0,
                //Vat        = 0
            };

            _orderRepository.Create(order);

            // Get all products in one shot, so we can add the product reference to each order detail
            var bookIds = itemsArray.Select(x => x.BookId).ToArray();
            var books   = _bookRepository.Fetch(x => bookIds.Contains(x.Id)).ToArray();

            // Create an order detail for each item
            foreach (var item in itemsArray)
            {
                var book = books.Single(x => x.Id == item.BookId);

                var detail = new OrderDetailRecord {
                    OrderRecord_Id = order.Id,
                    BookId         = book.Id,
                    Quantity       = item.Quantity,
                    UnitPrice      = book.UnitPrice,
                    VatRate        = .19m
                };

                _orderDetailRepository.Create(detail);
                order.Details.Add(detail);
            }

            order.UpdateTotals();

            return(order);
        }