public ActionResult Edit(int id) { Buying buying; BuyingsViewModel model = new BuyingsViewModel(); using (var context = new ApplicationDbContext()) { IUnitOfWork unitOfWork = new UnitOfWork(context); buying = unitOfWork.Buyings.FirstOrDefault(x => x.Id == id); if (buying == null) { return(NotFound()); } model.Buying = buying; model.ManagerName = buying.Manager.Name; model.ManagerSecondName = buying.Manager.SecondName; model.Buyer = buying.Buyer.FullName; model.Product = buying.Product.Name; model.PurchaseDate = buying.PurchaseDate; model.Cost = buying.Cost; } return(View(model)); }
public async Task <ActionResult> Edit(BuyingsViewModel model) { if (ModelState.IsValid) { using (var context = new ApplicationDbContext()) { IUnitOfWork unitOfWork = new UnitOfWork(context); Buying buying = unitOfWork.Buyings.FirstOrDefault(x => x.Id == model.Buying.Id); if (buying == null) { return(NotFound()); } Manager manager = unitOfWork.Managers.FirstOrDefault(x => x.Name == model.ManagerName && x.SecondName == model.ManagerSecondName); Buyer buyer = unitOfWork.Buyers.FirstOrDefault(x => x.FullName == model.Buyer); Product product = unitOfWork.Products.FirstOrDefault(x => x.Name == model.Product); if (manager == null) { buying.Manager = new Manager() { Name = model.ManagerName, SecondName = model.ManagerSecondName }; } else { buying.Manager = manager; } if (buyer == null) { buying.Buyer = new Buyer() { FullName = model.Buyer }; } else { buying.Buyer = buyer; } if (product == null) { buying.Product = new Product() { Name = model.Product, Cost = model.Cost }; } else { buying.Product = product; } buying.PurchaseDate = model.PurchaseDate; buying.Cost = model.Cost; try { await unitOfWork.SaveAsync(); } catch (Exception e) { Log.Error($"ManagersController.Edit: Ошибка при попытке сохранения изменений покупки: {DateTime.Now}" + $"{Environment.NewLine}{e}{Environment.NewLine}"); throw new Exception($"Ошибка при попытке сохранения изменений покупки: {e}"); } } } return(View("Index")); }