Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ child records null

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;
    }
}
like image 668
l15a Avatar asked Jul 20 '12 15:07

l15a


1 Answers

Am I wrong to think that the child records will be populated?

I'm guessing that it could be that the DaysOff is populated lazily, but by that point EmployeeEntities has been disposed. You might want to try something like:

using (var db = new EmployeeEntities().Include("Employee.DaysOff"))

Also note that your code in the using statement would be simpler written as:

return db.Employees.FirstOrDefault(e => e.EmployeeId == employeeId);

Edit

The code above is not correct. Include must be used on an ObjectQuery<T> or IQueryable<T> and can't be applied to an ObjectContext/DbContext. Correct usage is:

using (var db = new EmployeeEntities())
{
    return db.Employees.Include("DaysOff")
        .FirstOrDefault(e => e.EmployeeId == employeeId);
}
like image 103
Jon Skeet Avatar answered Sep 28 '22 07:09

Jon Skeet