简体   繁体   English

ASP.NET Web API DELETE方法错误

[英]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. 使用带有实体框架的ASP.NET Web API DELETE方法传递学生ID,如果表中存在id,则删除记录。 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)" “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 chck for null id comes first that can also be resole your issue, check below code 另一件事是方法应该是快速失败所以在你的情况下,所以chck for 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();
}

as you are expecting only one student going to have ID ,as ID is prmary key which is incremental number than you should use SingleOrDeault() , do not use FirstOrDefault() as there cannot be more student with same id 因为你期望只有一个学生会有ID,因为ID是prmary key,它是增量号,而不是你应该使用SingleOrDeault() ,所以不要使用FirstOrDefault()因为不能有更多同一个id的学生

var student = sd.Students
            .Where(s => s.StudentID == id)
            .SingleOrDeault();
if(student!=null)
{
  //perform operation
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM