0

Controller Code

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 Code

$.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);
    }
});

I got this error: 500 Internal Server Error : The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.

Pankaj
  • 9,749
  • 32
  • 139
  • 283
  • Don't wrap the query in `using` Refer [these answers](http://stackoverflow.com/questions/18398356/how-to-solve-the-error-the-objectcontext-instance-has-been-disposed-and-can-no-l) for more explanation. –  May 20 '17 at 08:18

1 Answers1

1

Your using wrap can cause this error because of Entity Framework's lazy-loading attribute. And it disposes context before entities are returned.

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 });
    }

You could remove using wrap to use eager loading for avoid the error you are facing:

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 });
kkakkurt
  • 2,790
  • 1
  • 30
  • 33