paone
paone

Reputation: 937

ASP.NET Web API DELETE method error

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

Upvotes: 3

Views: 1488

Answers (2)

Pranay Rana
Pranay Rana

Reputation: 176896

Another thing is method should be fast fail so in you case, so check for null id comes first that can also be resole your issue, check this 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 which is the primary key and is an incremental number, then 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
}

Upvotes: 1

Emre Kabaoglu
Emre Kabaoglu

Reputation: 13146

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

Upvotes: 2

Related Questions