title: Linq SelectMany include parent
body: <p>I have the following three Linq To Sql entities: Location, Institution, and Building. </p>
  
  <p>The Location table is simply a LocationId, and LocationTypeId. </p>
  
  <p>Institution and Building both get their Ids from the Location table in a one to one relationship, and the Institution table has a one to many relationship with the Building table. </p>
  
  <p>I am trying to return all location records for an institution and all of its children. The following query returns what I need except that it is missing the parent Institution location record. </p>
  
  <pre><code>var query = dc.Locations.SelectMany(l =&gt; l.Institutions, (loc, inst) =&gt; new { loc, inst })
                          .SelectMany(i =&gt; i.inst.Buildings, (locInst, bld) =&gt; bld.Location );
  </code></pre>
  
  <p>How can I include the parent along  with the children?</p>
  
  <p><a href="https://i.stack.imgur.com/z1YO0.png" rel="noreferrer"><img src="https://i.stack.imgur.com/z1YO0.png" alt="ERD with relevant columns"></a></p>
  
  <p><strong>UPDATE:</strong></p>
  
  <p>I can get the records I want if I use a union on the original location query, but I am still wondering if this is the best solution. Here is the code with the Union.</p>
  
  <pre><code>IQueryable&lt;Location&gt; locations = dc.Locations;
  
  locations.SelectMany(l =&gt; l.Institutions, (loc, inst) =&gt; new { loc, inst })
           .SelectMany(i =&gt; i.inst.Buildings, (locInst, bld) =&gt; bld.Location)
           .Union(locations);
  </code></pre>