ASP.NET Web API DELETE方法错误

vatpfxk5  于 2023-05-19  发布在  .NET
关注(0)|答案(2)|浏览(160)

使用API方法和实体框架传递学生ID,如果该ID存在于表中,则删除记录。当我尝试测试它时,我得到以下错误消息

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

hsvhsicv1#

你应该检查学生是否存在;

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

x33g5p2x2#

另一件事是方法应该快速失败,所以在你的情况下,首先检查null id,这也可以解决你的问题,检查这段代码:

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

由于您预计只有一个学生将拥有ID,它是主键并且是一个递增的数字,因此您应该使用SingleOrDeault(),不要使用FirstOrDefault(),因为不能有更多的学生具有相同的id

var student = sd.Students
                .Where(s => s.StudentID == id)
                .SingleOrDeault();

if (student != null)
{
    // perform operation
}

相关问题