title: Can this EF query be optimized?
body: <p>I'm new to Entity Framework and uncertain as to when to use eager loading and <code>Include</code>, when to use LINQ queries with <code>Select</code>, and when to load entities on demand. I also don't know if and when EF caches entities. (Yes, I'll read the docs eventually :-)</p>
  
  <p>I'm building a messaging system internal to ASP .NET MVC website, and performance is going to be really important. Imagine the following scenario.</p>
  
  <p>When Rihanna goes into her inbox, she needs to see a list of messages, each with sender's name and picture. Imagine John wrote Rihanna lyrics to his new song. In her inbox, there is a message with John's picture. When John goes into his outbox, he sees the same message with Rihanna's name and picture. </p>
  
  <p>So, when we grab a message from the database, we might need both sender and recipient profile pictures. Imagine the following query:</p>
  
  <pre><code>private static Func&lt;MyEntities, int, Message&gt; _getMessageByIdQuery = CompiledQuery.Compile(
      ( MyEntities ctx, int messageId ) =&gt; ctx.Messages
          .Include( "SenderUser" )
          .Include( "SenderUser.UserProfile.Image" )
          .Include( "RecipientUser" )
          .Include( "RecipientUser.UserProfile.Image" )
          .SingleOrDefault( message =&gt; message.ID == messageId ) );
  </code></pre>
  
  <p>Will this query be efficient? Is there any way to load <code>SenderUser.UserProfile.Image</code> without loading <code>SenderUser</code>, considering <code>User.ID</code> and <code>UserProfile.UserID</code> are one-to-one? I imagine I would need to use LINQ JOIN's for this. Is this correct?</p>
  
  <p>Is it more efficient to use LINQ to avoid loading all fields when only one is needed (e.g. only load <code>ImageID</code> from <code>UserProfile</code>)?</p>
  
  <p>Is it better to do the same using <code>Load</code> somewhere in code?</p>
  
  <p>Does such query go to the database each time? Imagine we had a thousand messages, all from the same person. Would we query for his <code>Image</code> each time?</p>
  
  <p>I'm using EF 4 and ASP .NET MVC 3.</p>
  
  <p>Thanks.</p>