Web API on dependency injection

Mogomotsi Motlhasedi 40 Reputation points
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?

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,614 questions
ASP.NET API
ASP.NET API
ASP.NET: A set of technologies in the .NET Framework for building web applications and XML web services.API: A software intermediary that allows two applications to interact with each other.
343 questions
{count} votes

2 answers

Sort by: Most helpful
  1. Bruce (SqlWork.com) 66,706 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.

    0 comments No comments

  2. SurferOnWww 3,201 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();
    }
    
    0 comments No comments

Your answer

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