I used Entity Framework to create my database schema and generate my code. I have a table called Employee that has child records in a DaysOff table. DaysOff has a foreign key to Employee and there is a 1 to * association in my model. I ran a LINQ query on the Employee table and expected that my Domain.Employee object would be populated with the DaysOff but the DaysOff are null. When I drill down in the Object I see “employee.DaysOff.Count threw an exception of type System.ObjectDisposedException”. Am I wrong to think that the child records will be populated? How would I do this? Here is the method I call to get my Employee:
public static Domain.Employee SelectEmployee(int employeeId)
{
using (var db = new EmployeeEntities())
{
Domain.Employee emp = (from e in db.Employees
where e.EmployeeId == employeeId
select e
).FirstOrDefault();
return emp;
}
}
EDIT:
A combination of the accepted answer below and the comments (all up-voted) helped me to solve this (yay!):
public static Domain.Employee SelectEmployee(int employeeId)
{
using (var db = new EmployeeEntities())
{
Domain.Employee emp = (from e in db.Employees.Include("DaysOff")
where e.EmployeeId == employeeId
select e).FirstOrDefault();
return emp;
}
}
I’m guessing that it could be that the
DaysOffis populated lazily, but by that pointEmployeeEntitieshas been disposed. You might want to try something like:Also note that your code in the
usingstatement would be simpler written as:Edit
The code above is not correct.
Includemust be used on anObjectQuery<T>orIQueryable<T>and can’t be applied to anObjectContext/DbContext. Correct usage is: