Share via

Web API on dependency injection

Anonymous
2023-11-13T08:33:16.2833333+00:00

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, considering the requirement to add a private method for this purpose?

Developer technologies | ASP.NET Core | Other
Developer technologies | ASP.NET Core | ASP.NET API

2 answers

Sort by: Most helpful
  1. SurferOnWww 6,016 Reputation points
    2023-11-15T01:12:39.64+00:00

    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();
    }
    

    Was this answer helpful?

    0 comments No comments

  2. Bruce (SqlWork.com) 84,066 Reputation points
    2023-11-14T16:56:59.2566667+00:00

    also you can run into race conditions, if check and insert are coded with the proper locking. You don't specify your concurrency requirements. EF supports optimistic concurrency if timestamps are used.

    also not clear what the question has to do with the title.

    Was this answer helpful?

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.