I am using EF 4 to retrieve a list of Employees.
public ContentResult AutoCompleteResult(string searchText)
{
List list = Employee.GetAll
Thought I would chime in here with my 2 cents. We had a very big data access layer, and one of the programmers was used to using a using statement for the context like so:
using (EntityModel myContext = EntityConnection)
{
//code in here to grab data
}
We are using the EntityConnection as a static property that serves up a dbContext per current HttpContext. Any method called after his using block would throw the exception 'ObjectContext instance has been disposed' since obviously the context was disposed of after his method call. So if you are only using one entity context per HttpContext, make sure you don't allow the garbage collector to dispose of it by using a using block.
I figured I would throw this in the answers since I know a lot of people use the entity context differently and I see a lot of using blocks in code samples out there.
I worth taking a look at your Employee object and make sure you don't have any virtual keywords sticking out there. The virtual keyword is interpreted by Entity Framework as 'lazy-load'. We'd need to see your Employee class to make an absolute assertion why you could be seeing the exception.
I prefer to just load up a fat instance declared outside of the using
Customer _custObj;
using (RazorOne rz1 = new RazorOne())
{
_custObj = rz1.Customers.FirstOrDefault(); // .Include = Lazy loading
// Versus Implicit Load
_custObj.AddressReference.Load();
_custObj.Address1Reference.Load();
}
Then I can pass her onto the View or whatever helper really wanted her..
I had the same problem and could resolve it by selecting a projection of the object with only the properties required by the caller, instead of returning the complete object. It seems that when you have many relations in your object, the serializer tries to navigate those.
So, (supposing that your object context is called "Entities") i would try something like this:
using ( Entities context = new Entities() )
{
var employeeProjection = (from e in context.Employee
select new { e.Id, c.FirstName, e.LastName }).ToList();
return employeeProjection;
}