【发布时间】:2021-06-02 00:10:19
【问题描述】:
我正在使用 web api put 方法。我需要更新数据库中的两列。但我在更新这两列时遇到了问题。
我有一个错误如下所述
System.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);
}
}
}
需要一些关于这个问题的建议。
【问题讨论】:
-
您的 PUT 请求是什么样的?
-
@Jasen, ,我想将姓名和员工编号更新到数据库中。姓名和员工编号将从其他用户开发的另一个 API 中获取。
-
你需要弄清楚为什么
emp(发送给API的模型)是null。
标签: asp.net api entity-framework asp.net-web-api