public async Task <Order> Create(Order orderToCreate, IList <ProductItem> orderedProductsData) { Order order = new Order() { PlacementDate = orderToCreate?.PlacementDate ?? DateTime.MinValue, Customer = orderToCreate.Customer, RecipientName = orderToCreate.RecipientName, RecipientAddress = orderToCreate.RecipientAddress, RecipientPhone = orderToCreate.RecipientPhone, }; var orderedProducts = new List <OrderedProduct>(); var products = await _context.Products .Include(p => p.OrderedProducts) .ThenInclude(op => op.Order) .ToListAsync(); foreach (var productItem in orderedProductsData) { var product = products.FirstOrDefault(p => p.ID == productItem.Product.ID); var orderedProduct = new OrderedProduct { Product = product, Order = order, Quantity = productItem.Quantity }; product.OrderedProducts.Add(orderedProduct); if (product.Stock - productItem.Quantity >= 0) { product.Stock = product.Stock - productItem.Quantity; } else { throw new DbUpdateException(); } orderedProducts.Add(orderedProduct); _context.Update(product); } order.OrderedProducts = orderedProducts; _context.Add(order); await _context.SaveChangesAsync(); return(order); }
public async Task <ImportOrder> Create(ImportOrder orderToCreate, IList <ProductItem> importedProductsData) { ImportOrder order = new ImportOrder() { PlacementDate = orderToCreate?.PlacementDate ?? DateTime.MinValue, WholesalerName = orderToCreate.WholesalerName, WholesalerAddress = orderToCreate.WholesalerAddress, WholesalerPhone = orderToCreate.WholesalerPhone, }; var importedProducts = new List <ImportedProduct>(); var productsQuery = _context.Products .Include(p => p.ImportedProducts) .ThenInclude(op => op.ImportOrder); foreach (var productItem in importedProductsData) { var product = await productsQuery .FirstOrDefaultAsync(p => p.ID == productItem.Product.ID); var importedProduct = new ImportedProduct { Product = product, ImportOrder = order, Quantity = productItem.Quantity }; product.ImportedProducts.Add(importedProduct); product.Stock = product.Stock + productItem.Quantity; importedProducts.Add(importedProduct); _context.Update(product); } order.ImportedProducts = importedProducts; _context.Add(order); await _context.SaveChangesAsync(); return(order); }
public void CreateProduct(Product p) { context.Add(p); context.SaveChanges(); }
public void CreateProduct(Product product) { _context.Add(product); _context.SaveChanges(); }