AlecTech
AlecTech

Reputation: 63

Trying to auto-increment counter during edit in ASP.NET Core Entity Framework

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):

enter image description here

When I use the other version of code, everything else can be changed/updated but TimesModified doesn't get incremented:

enter image description here

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:

enter image description here

Any suggestions?

1st suggestion is giving following error:

enter image description here

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) enter image description here

enter image description here

enter image description here

3rd suggestion my final SOLUTION!!!

added extra input field inside Edit View

enter image description here

Inside Edit Action , doing update in 2 steps: Save input , increment, Save again.

enter image description here

Upvotes: 1

Views: 1033

Answers (3)

AlecTech
AlecTech

Reputation: 63

3rd suggestion my final SOLUTION!!!

added extra input field inside Edit View enter image description here

Inside Edit Action , doing update in 2 steps: Save input , increment, Save again.

enter image description here

Upvotes: 0

Serge
Serge

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

David Browne - Microsoft
David Browne - Microsoft

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

Related Questions