HI WELCOME TO SIRIS

Implementing Delete method in ASP.NET Web API

Leave a Comment
 we will discuss implementing DELETE method in ASP.NET Web API. Delete allows us to delete an item.



We want to delete the specified employee from the Employees table. Include the following Delete() method in EmployeesController.

public void Delete(int id)
{
    using (EmployeeDBEntities entities = new EmployeeDBEntities())
    {
        entities.Employees.Remove(entities.Employees.FirstOrDefault(e => e.ID == id));
        entities.SaveChanges();
    }
}

There are 3 problems with the above code
  1. The above code deletes the employee only when the ID of the employee that you want to delete exists.
  2. When the deletion is successful, since the method return type is void we get status code 204 No Content. We should be returning status code 200 OK.
  3. If the ID of the employee that we want to delete does not exist, there is an exception and as a result of it the Web API returns status code 500 internal server error. If an item is not found, we should be returning status code 404 Not Found.
To fix all the above problems, modify the code in Delete() method as shown below

public HttpResponseMessage Delete(int id)
{
    try
    {
        using (EmployeeDBEntities entities = new EmployeeDBEntities())
        {
            var entity = entities.Employees.FirstOrDefault(e => e.ID == id);
            if (entity == null)
            {
                return Request.CreateErrorResponse(HttpStatusCode.NotFound,
                    "Employee with Id = " + id.ToString() + " not found to delete");
            }
            else
            {
                entities.Employees.Remove(entity);
                entities.SaveChanges();
                return Request.CreateResponse(HttpStatusCode.OK);
            }
        }
    }
    catch (Exception ex)
    {
        return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
    }
}

0 comments:

Post a Comment

Note: only a member of this blog may post a comment.