title: EF Eager load related entities from related entity
body: <p>I'm having difficulties with eagerly loading a complex relation type. Consider my entities:</p>
  
  <pre><code>public class User
  {
      public string UserName { get; set; }
  }
  
  public class Ownership
  {
      public User   Owner  { get; set; }
      public Device Device { get; set; }
  }
  
  public class Device
  {
      public License License { get; set; }
  }
  </code></pre>
  
  <p>Assume that all entities are in separate tables. I left out all the non-essential convention code. I can post more when needed.</p>
  
  <p>My query:</p>
  
  <pre><code>var result = return context.Ownerships
                .Include(o =&gt; o.Device.License)
                .Where(o =&gt; o.Owner.UserName == userName)
                .Select(o =&gt; o.Device).ToList();
  </code></pre>
  
  <p>But this results in <code>null</code> valued licenses for all devices. However if I define the License like this:</p>
  
  <pre><code>public class Device
  {
      public virtual License License { get; set; }
  }
  </code></pre>
  
  <p>And query like this:</p>
  
  <pre><code>var result = return context.Ownerships
                .Where(o =&gt; o.Owner.UserName == userName)
                .Select(o =&gt; o.Device).ToList();
  </code></pre>
  
  <p>It works (License is not <code>null</code> for devices) but I rather not lazy load by default. The entities are served over rest so, by serialization, I get license info for each device that I query which is a lot of data over the line I don't need.</p>
  
  <p>Any hints?</p>
  
  <p><strong>Solution</strong></p>
  
  <pre><code>var result = return context.Ownerships
      .Where(o =&gt; o.Owner.UserName == userName)
      .Select(o =&gt; o.Device)
          .Include(d =&gt; d.License)
          .ToList();
  </code></pre>