I'm new here and I'm fighting with adding 2 lines/rows at 2 different tables using only on event. I have the following event which is working for the 'transactionModel'. I'd like to add the row/line at the CostCenterModel. Can you help me with it? Here is
part of the code below:
I've highlighted in Yellow part of the code that isn't working.
public async Task<IActionResult> AddOrEdit(int id, [Bind("TransactionId,AccountNumber,BeneficiaryName,BankName,SWIFTCode,Amount,Date")] TransactionModel transactionModel)
{
if (ModelState.IsValid)
{
//Insert
if (id == 0)
{
transactionModel.Date = DateTime.Now;
_context.Add(transactionModel);
await _contextNew.SaveChangesAsync();
CostCenterModel costcenterModel = new CostCenterModel();
.NET forums are moving to a new home on Microsoft Q&A, we encourage you to go to Microsoft Q&A for .NET for posting new questions and get involved today.
None
0 Points
1 Post
Add row to different tables at only single one event (Microsoft ASP.NET CORE MVC)
Feb 15, 2021 10:47 PM|Paulo Zampieri|LINK
Hi,
I'm new here and I'm fighting with adding 2 lines/rows at 2 different tables using only on event. I have the following event which is working for the 'transactionModel'. I'd like to add the row/line at the CostCenterModel. Can you help me with it? Here is part of the code below:
I've highlighted in Yellow part of the code that isn't working.
public async Task<IActionResult> AddOrEdit(int id, [Bind("TransactionId,AccountNumber,BeneficiaryName,BankName,SWIFTCode,Amount,Date")] TransactionModel transactionModel)
{
if (ModelState.IsValid)
{
//Insert
if (id == 0)
{
transactionModel.Date = DateTime.Now;
_context.Add(transactionModel);
await _contextNew.SaveChangesAsync();
CostCenterModel costcenterModel = new CostCenterModel();
costcenterModel.CosCenterid = 12;
costcenterModel.Department = "Added manually";
costcenterModel.Description = "Description added manually";
await _context.CostCenter.AddAsync(costcenterModel);
await _contextNew.SaveChangesAsync();
//Update
else
{
try
{
_context.Update(transactionModel);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!TransactionModelExists(transactionModel.TransactionId))
{ return NotFound(); }
else
{ throw; }
}
}
return Json(new { isValid = true, html = Helper.RenderRazorViewToString(this, "_ViewAll", _context.Transactions.ToList()) });
}
return Json(new { isValid = false, html = Helper.RenderRazorViewToString(this, "AddOrEdit", transactionModel) });
}
}
Contributor
2700 Points
777 Posts
Re: Add row to different tables at only single one event (Microsoft ASP.NET CORE MVC)
Feb 16, 2021 07:23 AM|YihuiSun|LINK
Hi Paulo Zampieri,
The context used to add entities is different from the context of SaveChanges.You need to modify your code:
Best Regards,
YihuiSun