控制器代码
public ActionResult SearchByUPC_Name(String keyword)
{
using (DbPOSEntities db = new DbPOSEntities())
{
var CompanyID = ((UserModel)Session["User"]).CompanyID;
var items = db.tblItems.Where(i => i.CompanyID == CompanyID
&& i.IsDeleted == false
&& (i.UPC == keyword || i.Name.Contains(keyword))).ToList();
return Json(new { Success = true, Items = items });
}
}
Js代码
$.ajax({
url: "/Item/SearchByUPC_Name",
type: "POST",
async: true,
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ "keyword": searchStr }),
dataType: "json",
success: function (response) {
debugger;
if (response.Success) {
console.log('ok');
}
else {
console.log('not ok');
}
},
error: function (err) {
alert(err.statusText);
}
});
我收到此错误: 500内部服务器错误:ObjectContext实例已被处理,无法再用于需要连接的操作。
答案 0 :(得分:1)
由于Entity Framework的延迟加载属性,您的using
换行可能会导致此错误。它在返回实体之前处理上下文。
using (DbPOSEntities db = new DbPOSEntities())
{
var CompanyID = ((UserModel)Session["User"]).CompanyID;
var items = db.tblItems.Where(i => i.CompanyID == CompanyID
&& i.IsDeleted == false
&& (i.UPC == keyword || i.Name.Contains(keyword))).ToList();
return Json(new { Success = true, Items = items });
}
您可以删除using
换行以使用预先加载来避免您遇到的错误:
DbPOSEntities db = new DbPOSEntities();
var CompanyID = ((UserModel)Session["User"]).CompanyID;
var items = db.tblItems.Where(i => i.CompanyID == CompanyID
&& i.IsDeleted == false
&& (i.UPC == keyword || i.Name.Contains(keyword))).ToList();
return Json(new { Success = true, Items = items });