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();
}
}
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();
}
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With