I'm creating a new project trying to use Generics as much as possible, but I've encountered an issue when doing HttpPut and using EF Core.
I'm using SQL Server in a container to store temporary data.
I keep getting the "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."
I've tried using _context.Update(entity) as well and it didn't work... I'm not sure what's going on... Maybe it's because I'm using a generic Service and Repo access?
Here's the code:
Controller:
[HttpPut("{id}")]
public async Task<IActionResult> UpdateMedicalRecord(int id, MedicalRecord medicalRecord)
{
if (_mediTrackService is null)
{
throw new Exception("Service not found");
}
try
{
var data = await _mediTrackService.GetDataByIdAsync(id);
if (data is null)
{
return NotFound();
}
await _mediTrackService.UpdateExistingAsync(medicalRecord);
return Created();
}
catch (Exception e)
{
throw new Exception($"{e.Message}");
}
}
Service:
public async Task UpdateExistingAsync(T entity)
{
try
{
await _mediTrackRepo.UpdateExistingAsync(entity);
}
catch (Exception e)
{
throw new Exception(e.Message);
}
}
Repository:
public async Task UpdateExistingAsync(T entity)
{
_context.Entry(entity).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException ex)
{
throw new DbUpdateConcurrencyException(ex.Message);
}
}
DbSetand nother abstraction over abstraction. Why? Remove repository layer, if you have services. In service introduceUpdateMedicalRecord(int id, MedicalRecord medicalRecord) { var existing = _context.MedicalRecords.Find(Id); _context.Entry(existing).CurrentValues.SetValues(medicalRecord); _context.SaveChanges() }Microsoft.EntityFrameworkCorepackage it is just super abstract repository layer with UoW. It is abstraction over databases, for sure If you do not plan in nearest future use other ORM.