Entity Framework - Include multiple level properties

c# entity-framework

Question

I'm attempting to use entity framework to retrieve a table from a database.

The table refers to another table, which in turn refers to more tables. I am aware of how to incorporate other tables. And this page on MSDN answer, which includes numerous levels, and the this response are as follows:

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

However, how would you include another table at level 3?

This doesn't seem to work:

entity.TableLevel1
          .Include(tLvl1=>tLvl1.TableLevel2
               .Select(tLvl2=>tLvl2.TableLevel3)
               .Select(tLvl2 => tLvl2.AnotherTableLevel3);
1
7
3/21/2018 9:50:05 AM

Accepted Answer

ZZZ_tmp
19
2/26/2016 3:22:40 PM

Popular Answer

You can create severalInclude() 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");

You can, however, designate your navigation properties asvirtual and will load slowly, thus there is no need to make theInclude() calls:

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

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

    public virtual TableLevel3 AnotherTableLevel3 { get; set; }
}


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow