views:

496

answers:

2

So I'm trying to work on a sample app. Trying to dig into ADO.NET Entity Framework. I get an employee back using a method with LINQ like this:

    public IList<Employee> FindByLastName(string lastName)
    {
        IList<Employee> emps;
        var e = from emp in _ctx.Employees where emp.LastName == lastName select emp;
            emps = e.ToList<Employee>();
        return emps;
    }

Then in one of my Unit Tests I have emps[0].Orders.Count > 0 and this comes back false. So my Orders property is not loading. What am I doing wrong?

UPDATE:
Any thoughts on how you incorporate this into this Load()/Include stuff into a repository pattern?

Do I have to do something lame like

public IList<Employee> GetEmployeeById(int id, bool includeOrders)
{

}
+2  A: 

Use the Include method, and you may be better writing the query less linq like:

public IList<Employee> FindByLastName(string lastName)    
{
    return _ctx.Employees
        .Include("Orders")
        .Where(emp => emp.LastName == lastName)
        .ToList();  
}
meandmycode
+1  A: 

You also have the option of using an Include statement to load your Orders.

public IList<Employee> FindByLastName(string lastName)
{
    IList<Employee> emps;
    var e = from emp in _ctx.Employees.Include("Orders") where emp.LastName == lastName select emp;
        emps = e.ToList<Employee>();
    return emps;
}

This will result in a more complex join at the SQL side, but it does have the benefit of a single trip to the database and a smaller scope of records than the Load() example would return. I'd try them both and see what works best for you.

Scroll Lock