3

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... Commented Dec 12, 2017 at 19:05
  • please do accept/upvote answer it works for you Commented Dec 12, 2017 at 19:30

2 Answers 2

2

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();
        }
Sign up to request clarification or add additional context in comments.

Comments

1

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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.