我使用的是一个web api put方法。我需要更新数据库中的两列。但我在更新这两个专栏时遇到了问题。
我在下面有一个错误
系统。NullReferenceException:"对象引用未设置为对象的实例。'
emp为空。
这是我当前的代码;
public class EmployeeController : ApiController
{
public HttpResponseMessage Put(int id, [FromBody] Employee emp)
{
try
{
using (EmpDBContext dbContext = new EmpDBContext())
{
var entity = dbContext.Employees.FirstOrDefault(e => e.Index == id);
if (entity != null)
{
entity.Name = emp.Name;
entity.EmpNum = emp.EmpNum;
dbContext.SaveChanges();
return Request.CreateResponse(HttpStatusCode.OK, entity);
}
else
{
return Request.CreateErrorResponse(HttpStatusCode.NotFound,
"Employee with Id " + id.ToString() + " not found to update");
}
}
}
catch (Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
}
}
}
需要一些关于这个问题的建议。
当您尝试使用c#中任何为null的值时,您将得到"Object reference error"。您需要查看API调用方法来检查emp变为空的原因。以下是可能性-
- 从调用方法传递参数名称应该和API参数中的名称完全相同,在您的情况下应该是emp
- 检查您的Employee Model是否与您的调用方法属性匹配
您可以从浏览器的"网络"选项卡中查看此信息。