谁能告诉我为什么以下代码在 api 控制器(MVC4)中不起作用?我收到一条错误消息,提示“无法访问已处置的对象”。我发现在其他情况下应该调用 ToList() 以便它强制执行查询。但就我而言,我使用的是 SingleOrDefault(),这不是立即在数据库上执行的吗?
public HttpResponseMessage GetPurchaseOrder(int POId)
{
PurchaseOrder po;
HttpResponseMessage resp;
using (PMDataDataContext database = new PMDataDataContext())
{
po = database.PurchaseOrders.SingleOrDefault(x => x.POId == POId);
if (po == null)
{
var message = string.Format("id = {0} not found", POId);
HttpError err = new HttpError(message);
resp = Request.CreateResponse(HttpStatusCode.NotFound, err);
}
else
{
resp = Request.CreateResponse(HttpStatusCode.OK, po);
}
}
return resp;
}