Reputation: 63
I need to auto-increment TimesModified
by 1 every time when Edit
method is run.
When I use the following code, only TimesModified
gets incremented but other parameters do not change (even though I'm changing let's say Age
):
When I use the other version of code, everything else can be changed/updated but TimesModified
doesn't get incremented:
I also tried this:
public async Task<IActionResult> Edit(int id, [Bind("ID,FirstName,LastName,Email,Phone,Age,City,Department,HiredDate,FiredDate,TimesModified")] Employee employee)
{
if (id != employee.ID)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
_context.Update(employee);
await _context.SaveChangesAsync();
_context.Update(employee.TimesModified++);
await _context.SaveChangesAsync();
}
}
}
And I get this error:
Any suggestions?
1st suggestion is giving following error:
2nd suggestion has no errors but when I change anything like Age for example, it resets back to original(prior to edit) value: (However TimesModified gets incremented ok)
3rd suggestion my final SOLUTION!!!
added extra input field inside Edit View
Inside Edit Action , doing update in 2 steps: Save input , increment, Save again.
Upvotes: 1
Views: 1033
Reputation: 63
3rd suggestion my final SOLUTION!!!
added extra input field inside Edit View
Inside Edit Action , doing update in 2 steps: Save input , increment, Save again.
Upvotes: 0
Reputation: 43890
Try this:
var employee = await _context.Employees
.Where(e => e.Id == employee.Id)
.FisrstOrDefaultAsync();
employee.TimesModified+= 1;
_context.Entry(employee).State = EntityState.Modified;
//or _context.Entry(employee).Property(t=>t.TimesModified).IsModified = true;
await _context.SaveChangesAsync();
Upvotes: 2
Reputation: 89141
Instead of fetching the whole entity, just query the TimesModified.
Eg
var tm = _context.Employees.Select(e => e.Id == employee.Id).Select(e => e.TimesModified).First();
employee.TimesModified = tm + 1;
_context.Update(employee);
await _context.SaveChangesAsync();
Upvotes: 0