Hi @
Anjali Agarwal
DbUpdateConcurrencyException: The database operation was expected to affect 1 row(s), but actually affected 0 row(s); data may have been modified or deleted since entities were loaded. See
http://go.microsoft.com/fwlink/?LinkId=527962
for information on understanding and handling optimistic concurrency exceptions.
The issue relates the EmployeeInfo primary key, you can try to set breakpoint to check the employeeInfo's EmployeeInfoId property, it might be the default value "0". When use the EntityState.Modified to modify the entity, the entity should exist in the database and have the primary key, once the item doesn't exist or have the primary key, it will show the above error.
To solve this issue, you can try to modify your code as below: In this sample, I just find the employee according to the employee number and the policy year, you can find a better way and based on your application to set the primary key when update the employeeinfo.
public async Task UpdateEmployee(EmployeeInfo employee)
//Query the database and get the primary key.
var empitem = _ackContext.EmployeeInfos.Where(x => x.EmployeeNumber== employee.EmployeeNumber && employee.PolicyYear==DateTime.Now.Year).AsNoTracking().FirstOrDefault();
if (empitem!=null)
employee.EmployeeInfoId = empitem.EmployeeInfoId; //based on the exist entity primary key to update the data.
employee.EmployeeInfoId = 0; //insert new entity.
_ackContext.Entry(employee).State= !_ackContext.EmployeeInfos.Any(x => x.EmployeeNumber== employee.EmployeeNumber && employee.PolicyYear==DateTime.Now.Year) ? EntityState.Added : EntityState.Modified
await _ackContext.SaveChangesAsync();
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
Best regards,
Dillion