public IActionResult Add(ProductAdd productViewModel) { if (ModelState.IsValid) { _dbContext.Products.Add(productViewModel.Product); _dbContext.SaveChanges(); return(RedirectToAction("Index", "UserProfile")); } return(View(productViewModel)); }
public IActionResult PrivateConfirmed(OrderSummary orderSummary) { //Transaction - if any DB update will go wrong performs rollback using (var transaction = _dbContext.Database.BeginTransaction()) { try { //Locks Products table - other users need to wait _dbContext.Database.ExecuteSqlCommand("SELECT TOP 0 NULL FROM Products WITH (TABLOCKX)"); if (!CheckCart()) { return(RedirectToAction("Index", "Cart")); } var order = orderSummary.Order; var myCart = orderSummary.OrderDetailsSummaryList; //Create separate order and separate order details for each seller var sellers = myCart.GroupBy(x => x.SellerId).Select(y => y.First().SellerName); foreach (var seller in sellers) { //Clone order var tmpOrder = new Order() { OrderId = order.OrderId, Date = order.Date, State = order.State, Name = order.Name, Surname = order.Surname, Address = order.Address, PostCode = order.PostCode, City = order.City, BuyerId = order.BuyerId, SellerId = _dbContext.Users.SingleOrDefault(x => x.UserName == seller).Id }; //Push tmpOrder to database _dbContext.Orders.Add(tmpOrder); _dbContext.SaveChanges(); //Get tmpOrder Order table Id var newId = tmpOrder.OrderId; //Map myCart to OrderDetails list. One per each seller var cartBySeller = myCart.Where(x => x.SellerName == seller); var tmp = new List <OrderDetail>(); foreach (var item in cartBySeller) { var pr = _dbContext.Products.SingleOrDefault(x => x.ProductId == item.ProductId); pr.Quantity -= item.Quantity; var newLine = new OrderDetail() { OrderDetailId = 0, OrderId = newId, Price = item.Price, ProductId = item.ProductId, Quantity = item.Quantity }; tmp.Add(newLine); } //Update OrderDetails table _dbContext.OrderDetails.AddRange(tmp); _dbContext.SaveChanges(); //Send out emails var userSeller = _dbContext.Users.SingleOrDefault(z => z.UserName == seller); var userBuyer = _dbContext.Users.SingleOrDefault(x => x.Id == GetUserId()); var mailing = new Mail(userBuyer, userSeller, tmpOrder, OrderStateEnum.Active, Configuration, cartBySeller, null); mailing.SendEmail(); } //Clear Cart Session Cart cart = GetCart(); cart.Clear(); SaveCart(cart); transaction.Commit(); } catch (Exception) { transaction.Rollback(); return(RedirectToAction("Index", "Home")); } } return(RedirectToAction("Index", "UserProfile")); }