3
votes

Using the ASP.NET Web API DELETE method with entity framework to pass the student id and if the id exists in the table delete the record. When I try to test it I get the following error message

"System.Data.Entity.Utilities.Check.NotNull[T](T value, String parameterName) System.Data.Entity.DbContext.Entry[TEntity](TEntity entity)"

public class StudentController : ApiController
{
    [HttpDelete]
    [Route("student/DeleteStudent/{id}")]

    public IHttpActionResult DeleteStudent(string id)
    {
        using (var sd = new SchoolDBEntities())
        {
            var student = sd.Students
                .Where(s => s.StudentID == id)
                .FirstOrDefault();

            sd.Entry(student).State = System.Data.Entity.EntityState.Deleted;
            sd.SaveChanges();
        }
        if (id == null)
        return BadRequest("Not a valid student id");

        return Ok();
    }
}
2
check my answer if (id == null) need to be done before you are doing delete operation...Pranay Rana
please do accept/upvote answer it works for youPranay Rana

2 Answers

2
votes

You should check that student exists;

        var student = sd.Students
            .Where(s => s.StudentID == id)
            .FirstOrDefault();
        if (student != null)
        {
            sd.Entry(student).State = System.Data.Entity.EntityState.Deleted;
            sd.SaveChanges();
        }
1
votes

another thing is method should be fast fail so in you case , so chck for null id comes first that can also be resole your issue, check below code

public IHttpActionResult DeleteStudent(string id)
 {
   if (id == null)
     return BadRequest("Not a valid student id");
       var student = sd.Students
                .Where(s => s.StudentID == id)
                .SingleOrDeault();
    if(student!=null)
    {
      //perform operation
    }    
    return Ok();
}

as you are expecting only one student going to have ID ,as ID is prmary key which is incremental number than you should use SingleOrDeault(), do not use FirstOrDefault() as there cannot be more student with same id

var student = sd.Students
            .Where(s => s.StudentID == id)
            .SingleOrDeault();
if(student!=null)
{
  //perform operation
}