Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
    }
}
like image 731
paone Avatar asked Mar 27 '26 21:03

paone


2 Answers

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();
        }
like image 176
lucky Avatar answered Mar 29 '26 11:03

lucky


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
}
like image 40
Pranay Rana Avatar answered Mar 29 '26 11:03

Pranay Rana



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!