20

I am trying to Eagerly load all the related entities or collection of Entity in one call. My Entities Looks like:

Class Person
{
    public virtual long Id { get; set; }
    public virtual string FirstName { get; set; }
    public virtual string LastName { get; set; }
}

Class Employee
{
    public virtual long Id { get; set; }
    public DateTime AppointmentDate { get; set; }
    public virtual ICollection<EmployeeTitle> Titles { get; set; }
    public virtual Person Person { get; set; }
}

Class EmployeeTitle
{
    public virtual long Id { get; set; }
    public virtual bool IsCurrent { get; set; } 
    public virtual Title Title { get; set; }
}
Class Title
{
    public virtual long Id { get; set; }
    public virtual string Code { get; set; }
    public virtual string Description { get; set; }
}

What Iam trying to do is if i call a method to load all Employees, the result should include Person, List of EmployeeTitles including the code and description from Title I have been able to get to the third level i.e. getting the Employee with person and list of EmployeeTitle. I don't know how to get the title information with the EmployeeTitle. My code to get this is:

Context.Employees.Include("Person").Include(e => e.Titles).ToList();

Please shed some light on how to accomplish this. Thanks in advance.

Jacob
  • 3,598
  • 4
  • 35
  • 56
Amit
  • 501
  • 1
  • 9
  • 16

2 Answers2

42

You can try this:

Context.Employees
    .Include(e => e.Person)
    .Include(e => e.Titles.Select(t => t.Title))
    .ToList();

Select can be applied to a collection and loads navigation properties of the next level in the object graph.

Slauma
  • 175,098
  • 59
  • 401
  • 420
  • 9
    IMPORTANT: Don't accidentally use the same variable for both lambda expressions `.Include(x => x.Titles.Select(x => x.Title))` or you'll get `Cannot convert lambda expression to type 'string' because it is not a delegate type` – Simon_Weaver May 11 '13 at 08:02
  • 5
    You must have "using System.Data.Entity", otherwise it will appear as this this overload doesn't exist. – Torben Junker Kjær Jan 13 '14 at 14:15
  • 1
    Is there a way I can achieve this using `Include(string)`? – Şafak Gür Mar 17 '14 at 12:34
  • 1
    @ŞafakGür: Yes, just use "dotted paths": `Include("Titles.Title")` – Slauma Mar 17 '14 at 17:28
  • +1 Took a while to finally come up with the right keywords in Google ("entity loading related collection that has collections") but this works :) – Matt Borja Jan 25 '16 at 23:33
5

Since this is the first page in my search in google, I just wanted to post this.

Slauma's answer is fine. But it's recommended to use Load() instead of ToList() if you don't plan to actually use the list. So it would be:

    Context.Employees
        .Include(e => e.Person)
        .Include(e => e.Titles.Select(t => t.Title))
        .Load();
makuvex
  • 51
  • 1
  • 1