I am using EF 4 to retrieve a list of Employees.
public ContentResult AutoCompleteResult(string searchText)
{
List list = Employee.GetAll
You could turn off lazy loading to resolve this problem.
Inside your 'using' block, try this:
yourObjectContext.ContextOptions.LazyLoadingEnabled = false;
After doing this, I was able to serialize my EF (DbContext-generated) POCO to JSON without any issue.
*Note: Since I've turned off lazy loading... I explicitly pull in related objects I need ahead of time (mostly with .Include() in my query) before the object is serialized to JSON.
I found the best way to handle this and keep the using statement you just need to use the include, see sample below:
using (var ctx = new Context(this.connectionString)) {
var query = ctx.[maintable]
.Include(x => x.[theothertable])
.FirstOrDefaultAsync(u => u.UserName.Equals(userName));
}
It sounds like some lazy-loading or delayed evaluation that's happening; you can't assume objects are "loaded" until you actually attempt to read from them.
You need to maintain your DataContext
until you are completely done handling the objects retrieved from the database to avoid these errors.
I had a variation on this problem. The data context was not closed, but the Object context instance has been disposed error was getting thrown anyway.
It turned out that the object had a self referential foreign key (ie the foreign key referred back into the same table). Accessing the navigation property in when it refers to a null, you get the objectcontext disposed exception instead of, say, a null pointer exception.
eg:
var a = myObject.Name; // works because myObject still has open object context
var b = myObject.SelfReference; // throws objectcontext disposed if SelfReference is null
It sounds like you have some lazily loaded relationship properties that have not yet loaded (which has an associated "n+1" performance concern). You can try eager loading to see if this helps; otherwise, explicitly load the data for each item in the list, before you close the object-context.
using (EmployeeContext db= new EmployeeContext())
{
var lst = db.Employees.Select(p=> new {
EmployeeID = p.EmployeeID,
Name = p.Name,
Salary = p.Salary,
Position = p.Position,
Age = p.Age,
Office = p.Office
}).ToList();
return Json(lst, JsonRequestBehavior.AllowGet);
}