public async Task <ActionResult> Edit([Bind(Include = "Id,CustomerName,CPUId,MotherboardId,PowerSupplyId,AssemblyNeeded,SelectedMemories")] PCViewModel model) { var motherboard = _motherboardService.Find(model.MotherboardId); var cpu = _cpuService.Find(model.CPUId); var powerSupply = _powerSupplyService.Find(model.PowerSupplyId); var selectedMemories = model.SelectedMemories.Where(item => item.IsSelected); if (ModelState.IsValid) { var message = ValidatePCConfiguration(motherboard, cpu, powerSupply, selectedMemories); if (!string.IsNullOrEmpty(message)) { ViewBag.ErrorMessage = message; LoadLists(); return(View(model)); } //begin a transaction _unitOfWork.BeginTransaction(); //setup the pc var oldPC = _pcService.Find(model.Id); oldPC.CustomerName = model.CustomerName; oldPC.CPUId = model.CPUId; oldPC.MotherboardId = model.MotherboardId; oldPC.PowerSupplyId = model.PowerSupplyId; oldPC.AssemblyNeeded = model.AssemblyNeeded; oldPC.TotalPrice = cpu.Price + motherboard.Price + powerSupply.Price + selectedMemories.Sum(item => item.Price * item.Count) + (model.AssemblyNeeded ? 50 : 0); //delete old selected memories for (int i = 0; i < oldPC.PCMemories.Count; i++) { _pcMemoryService.Delete(oldPC.PCMemories.ElementAt(i)); i--; } _unitOfWork.SaveChanges(); //add new selected memories foreach (var item in selectedMemories) { var pcMemory = new PCMemory { MemoryId = item.Id, PC = oldPC, Count = item.Count }; _pcMemoryService.Insert(pcMemory); } //save and commit all changes _unitOfWork.SaveChanges(); _unitOfWork.Commit(); return(RedirectToAction("Index")); } LoadLists(); return(View(model)); }
public async Task <ActionResult> Create([Bind(Include = "Id,CustomerName,CPUId,MotherboardId,PowerSupplyId,AssemblyNeeded,SelectedMemories")] PCViewModel model) { //get selected parts var motherboard = _motherboardService.Find(model.MotherboardId); var cpu = _cpuService.Find(model.CPUId); var powerSupply = _powerSupplyService.Find(model.PowerSupplyId); var selectedMemories = model.SelectedMemories.Where(item => item.IsSelected); if (ModelState.IsValid) { //validate pc configuration var message = ValidatePCConfiguration(motherboard, cpu, powerSupply, selectedMemories); if (!string.IsNullOrEmpty(message)) { //not cofigured well ViewBag.ErrorMessage = message; LoadLists(); return(View(model)); } //setup a new pc var newPC = _mapper.Map <PC>(model); //compute the price newPC.TotalPrice = cpu.Price + motherboard.Price + powerSupply.Price + selectedMemories.Sum(item => item.Price * item.Count) + (model.AssemblyNeeded ? 50 : 0); _pcService.Insert(newPC); //get selected memories foreach (var item in model.SelectedMemories.Where(item => item.IsSelected)) { var pcMemory = new PCMemory { MemoryId = item.Id, PC = newPC, Count = item.Count }; _pcMemoryService.Insert(pcMemory); } //save the changes _unitOfWork.SaveChanges(); return(RedirectToAction("Index")); } //if error load lists again LoadLists(); return(View(model)); }