private void CreateOrder(int number) { List <Customer> customerLst = _unitOfWork.CustomerRepository.GetAll(); List <Product> productLst = _unitOfWork.ProductRepository.GetAll(); Random random = new Random(); for (int i = 1; i < number + 1; i++) { int indexC = random.Next(0, customerLst.Count() - 1); Customer customer = customerLst.ToList()[indexC]; //Create OrderHeader Order order = new Order() { CustomerId = customer.Id, CreateDate = DateTime.Now, Total = 0, Status = OrderStatus.New, UpdatedDate = DateTime.Now }; _unitOfWork.OrderRepository.Add(order); // Create OrderLine for (int j = 0; j < 2; j++) { int indexP = random.Next(0, productLst.Count() - 1); Product p = productLst.ToList()[indexP]; OrderDetail detail = new OrderDetail() { Order = order, DiscountTotal = 0, Product = p, PromotionCode = "", Status = OrderLineStatus.Active, Quanity = 1, UPrice = 0, SubTotal = 0 }; //Add option IEnumerable <ProductOption> optLst = _unitOfWork.ProductOptionRepository.GetByProduct(p.Id); ProductOption selectedOpt = optLst.ToList()[0]; OrderDetailOption opt = new OrderDetailOption() { AdditionalCost = selectedOpt.AdditionalCost, OrderDetail = detail, OptionId = selectedOpt.Id }; //UPdate back to detail detail.SubTotal = (p.BasePrice + opt.AdditionalCost) * detail.Quanity - detail.DiscountTotal; order.Total += detail.SubTotal; _unitOfWork.OrderDetailRepository.Add(detail); _unitOfWork.OrderDetailOptionRepository.Add(opt); } _unitOfWork.Save(); } }
public async Task <bool> CreateOrderAsync(OrderDetailView orderView) { var validated = await ValidateDataAsync(orderView); if (!validated) { new RestException(HttpStatusCode.InternalServerError, new { order = "Invalid data" }); } Order order = new Order() { Id = 0, CreateDate = DateTime.Now, CustomerId = orderView.CustomerId, Status = OrderStatus.New, Total = orderView.Total, }; await _unitOfWork.OrderRepository.AddAsync(order); //OrderLine foreach (OrderLineView line in orderView.OrderLines) { OrderDetail detail = new OrderDetail() { Id = 0, Order = order, DiscountTotal = line.DiscountTotal, PromotionCode = line.PromotionCode, ProductiId = line.ProductiId, Quanity = line.Quanity, Status = CodeTranslation.ToOrderLineCode(line.Status), SubTotal = line.SubTotal, UPrice = line.UPrice }; await _unitOfWork.OrderDetailRepository.AddAsync(detail); //Options if (line.PurchasedOptions != null) { foreach (OrderLineOptionView opt in line.PurchasedOptions) { OrderDetailOption detailOpt = new OrderDetailOption() { Id = 0, AdditionalCost = opt.AdditionalCost, OptionId = opt.OptionId, OrderDetailID = opt.OrderDetailId, }; await _unitOfWork.OrderDetailOptionRepository.AddAsync(detailOpt); } } } var success = await _unitOfWork.SaveAsync() > 0; if (success) { return(success); } else { throw new RestException(HttpStatusCode.InternalServerError, new { order = "Unable to save order" }); } }