I have the following code in controller
public async Task<IActionResult> Post(string imei)
{
var device = await _dbContext.Devices.FirstOrDefaultAsync(x => x.Imei == imei);
if (device == null)
{
await _dbContext.Devices.AddAsync(new Device(imei));
await _dbContext.SaveChangesAsync();
}
else
{
throw new ConflictException($"Device with IMEI '{imei}' already exists");
}
return Ok();
}
It is hard to reproduce but sometimes I got
23505: duplicate key value violates unique constraint \"devices_imei_key\"
It seems that device
is null but when SaveChanges
it is already not null. How can I handle it avoid using try...catch
? Can I use AsNoTacking()
to improve reading from database?
try catch
with the specific exception for the duplicate key. Another option - create a stored procedure for inserting new devices and handle this scenario in there - but at some level you will have to deal with the exception.