7

I am trying to get a table from database using entity framework.

The table has reference to other table which again has reference to other tables. I know how to include other tables. And according to this answer and this MSDN page including multiple levels are like this:

entity.TableLevel1.Include(tLvl1=>tLvl1.TableLevel2.Select(tLvl2=>tLvl2.TableLevel3));

But my question is, how to include another table at level 3 ?

This seems not to work:

entity.TableLevel1
          .Include(tLvl1=>tLvl1.TableLevel2
               .Select(tLvl2=>tLvl2.TableLevel3)
               .Select(tLvl2 => tLvl2.AnotherTableLevel3);
Nawed Nabi Zada
  • 2,819
  • 5
  • 29
  • 40

3 Answers3

19

Add another Include call:

entity.TableLevel1.Include(tLvl1=>tLvl1.TableLevel2.Select(tLvl2=>tLvl2.TableLevel3))
                  .Include(tLvl1=>tLvl1.TableLevel2.Select(tLvl2=>tLvl2.AnotherTableLevel3));

If you want to load related entities that are at the same level you should call Include extension method for each of them.

ocuenca
  • 38,548
  • 11
  • 89
  • 102
6

You can make multiple Include() calls:

entity.TableLevel1.Include(t1 => t1.TableLevel2);
entity.TableLevel1.Include(t1 => t1.TableLevel2.Select(t2 => t2.TableLevel3));
entity.TableLevel1.Include(t1 => t1.TableLevel2.Select(t2 => t2.AnotherTableLevel3));

or

entity.TableLevel1.Include("TableLevel2");
entity.TableLevel1.Include("TableLevel2.TableLevel3");
entity.TableLevel1.Include("TableLevel2.AnotherTableLevel3");

But you can mark your navigation properties as virtual and will be lazy loading, so you dont need to make the Include() calls:

class TableLevel1
{
    public virtual TableLevel2 TableLevel2 { get; set; }
}

class TableLevel2
{
    public virtual TableLevel3 TableLevel3 { get; set; }

    public virtual TableLevel3 AnotherTableLevel3 { get; set; }
}
Arturo Menchaca
  • 15,783
  • 1
  • 29
  • 53
  • 4
    Arturo, there are two things I want to warn you about your solutions. The first thing is your first `Include` call is unnecessary, that level is going to be loaded with any of the other two `Include` calls. The second thing is if they want to use their entities in a place where its context was already disposed, lazy loading is not a option, an exception will be thrown. – ocuenca Feb 26 '16 at 15:36
0

Using EF 6.2 (not core) this gave me a headache for a few hours, only to find that the reason this wasn't working...

.Include("InspectionResultsByPerspective") .Include("InspectionResultsByPerspective.InspectionResults") .Include("InspectionResultsByPerspective.InspectionResults.PreparationTasksResults")

was because the type PreparationTasksResults had no default ctor!!! ahhh!

Give it a default ctor and you can include to your heart's content :) or so it seems for me

AceSyntax
  • 139
  • 1
  • 4