ASP NET CORE MVC - Can't update 2 tables in only one event.

Feb 16 2021 3:54 PM
Hi,
I'm trying to update 2 tables at the same time using only one event. Below is code, however, I can't make it work in second update described below.
 
The error is at the bottom of this page
 
Does anyone has any idea what's going on?
 
thanks in advance.
 
This is the code:
  1. [HttpPost]  
  2. [ValidateAntiForgeryToken]  
  3. public async Task<IActionResult> Edit(int id, [Bind("Companyid,Name,Code,Currency")] Company company)  
  4. {  
  5. if (id != company.Companyid)  
  6. {  
  7. return NotFound();  
  8. }  
  9. if (ModelState.IsValid)  
  10. {  
  11. try  
  12. {  
  13. TempData["Confirmation"] = company.Name + " was updated.";  
  14. _context.Update(company);  
  15. await _context.SaveChangesAsync();   
  16. //Until here, the code above works fine and no errors.  
  17.    
  18.    
  19. // this is the code that it insn't working. I have a second table 'CostCenter' which Key is CCid  
  20. // this is a simple update method I'm trying to implement.   
  21. int ccid = 1;  
  22. CostCenter costCenter = new CostCenter();  
  23. costCenter = _context.Costcenter.Find(ccid);  
  24. costCenter.Department = "Testing....";  
  25. _context.SaveChanges();  
  26. }  
  27. catch (DbUpdateConcurrencyException)  
  28. {  
  29. if (!CompanyExists(company.Companyid))  
  30. {  
  31. return NotFound();  
  32. }  
  33. else  
  34. {  
  35. throw;  
  36. }  
  37. }  
  38. return RedirectToAction(nameof(Index));  
  39. }  
  40. return View(company);  
  41. }  

Answers (3)