How can I check if a record exists in the database before performing operations like editing or deleting it in a .NET Core Web API
Below is an action method generated automatically by the Visual Studio 2022 using a scaffolding operation for deleting a record. Note that it checks if a record exists in the database before performing deletion. You will able to check it like below.
// DELETE: api/Movies/5
[HttpDelete("{id}")]
public async Task<IActionResult> DeleteMovie(int id)
{
var movie = await _context.Movie.FindAsync(id);
if (movie == null)
{
return NotFound();
}
_context.Movie.Remove(movie);
await _context.SaveChangesAsync();
return NoContent();
}