I have a DELETE and PUT method which contain the same code to get the list of Ids from the database and check to see if they exist before performing the action:
try
{
var ids =
(await _testTableTbRepository.GetAllAsync())
.Select(_ => new TestTableTbModel { Id = _.Id }).OfType<int>().ToList();
if (!ids.Contains(model.Id))
{
return StatusCode(400, "Id: " + model.Id + " does not exist");
}
await _testTableTbRepository.DeleteAsync(model.Id);
return Ok(model.Id);
}
catch (Exception e)
{
return StatusCode(500, e);
}
My thought is that the conversion of Ids to integers is not working as it should, so it keeps getting caught at the if-statement and returning a 400 status. Does anyone see anything wrong with this? Is there a better way to write this?
Why all this hassle? Let DB Help you Use DBException instead.
This way you wont load a huge db in your memory and save one giant call plus all that select and contain checks.
try
{
await _testTableTbRepository.DeleteAsync(model.Id);
return Ok(model.Id);
}
catch(DbException e)
{
return StatusCode(404, "Id: " + model.Id + " does not exist");
}
catch (Exception e)
{
return StatusCode(500, e);
}
Thanks @Fran for pointing out 400 -> 404