Selecting nested navigation properties will generate the same SQL statement when selecting separate navigation properties

StackOverflow https://stackoverflow.com/questions/17605420

  •  02-06-2022
  •  | 
  •  

Question

I have the following repository method:-

public AccountDefinition GetCustomer2(int id)
        {      var c = entities.AccountDefinitions.Where(p => p.ORG_ID == id)
               .Include(a => a.SDOrganization)
               .Include(a2 => a2.SiteDefinitions)
                .Include(a3 => a3.SDOrganization.AaaPostalAddresses)
                .Include(a4 => a4.SiteDefinitions.Select(a5 => a5.DepartmentDefinitions.Select(a6 => a6.SDUsers.Select(a7 => a7.AaaUser.AaaContactInfoes)))).SingleOrDefault();
return c; }

But when I comment some code I found that the generated SQL statement when calling the Action method will be the same:-

public AccountDefinition GetCustomer2(int id)
        {      var c = entities.AccountDefinitions.Where(p => p.ORG_ID == id)
           //    .Include(a => a.SDOrganization)
            //   .Include(a2 => a2.SiteDefinitions)
                .Include(a3 => a3.SDOrganization.AaaPostalAddresses)
                .Include(a4 => a4.SiteDefinitions.Select(a5 => a5.DepartmentDefinitions.Select(a6 => a6.SDUsers.Select(a7 => a7.AaaUser.AaaContactInfoes)))).SingleOrDefault();
return c; }

So does this mean when I navigate to a nested Navigation property , then EF will automatically retrieve parent navigation properties also? . so for example when i write .Include(a3 => a3.SDOrganization.AaaPostalAddresses) , then there is no need to write .Include(a => a.SDOrganization)

Was it helpful?

Solution

In a nutshell yes, it has to otherwise there is no way for you to traverse to that navigation property

EG, the only way to access AccountDefinition.SDOrganization.AaaPostalAddresses is if SDOrganization is not null.

Having said that my personal preference is to make this intermediate inclusion explicit by listing it anyway. While this has no functional benefit its a reminder that this property will also be returned

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top