public void EditProduct(Product product) { var DbProduct = _context.Products.First(p => p.Id == product.Id); if (product.Id == DbProduct.Id) { DbProduct.Name = product.Name; DbProduct.Price = product.Price; } else { _context.Products.Add(product); } _context.SaveChanges(); }
public Order CreateOrder(OrderViewModel orderViewModel, CartViewModel cartViewModel, string UserName) { var user = _userManager .FindByNameAsync(UserName) .Result; using (var trans = _context.Database.BeginTransaction()) { var order = new Order() { Name = orderViewModel.Name, Address = orderViewModel.Address, Date = DateTime.Now, Phone = orderViewModel.Phone, User = user }; _context.Orders.Add(order); foreach (var item in cartViewModel.Items) { var productVm = item.Key; var product = _context.Products.FirstOrDefault(p => p.Id == productVm.Id); if (product == null) { throw new InvalidOperationException("Товар не найден в БД"); } var orderItem = new OrderItem() { Order = order, Product = product, Price = product.Price, Quantity = item.Value }; _context.OrderItems.Add(orderItem); } _context.SaveChanges(); trans.Commit(); return(order); } }