title: Entity Framework Navigation Properties on Views
body: <p>I am a little confused on how navigation properties work on MVC.</p>
  
  <p>Let's take a look at this code:</p>
  
  <pre><code>var messages = db.messages // .Include("user_reciever").Include("user_sender")
      .Where(M =&gt; M.receiver_id == _User.id &amp;&amp; M.delete_code != 1)
      .OrderByDescending(M =&gt; M.timestamp);
  
  return View(messages.ToList());
  </code></pre>
  
  <p>I excluded the Include field so "user_reciever" and "user_sender" are not included. </p>
  
  <p>However, in my View, I have this:</p>
  
  <pre><code>@foreach (var item in Model)
  {
      var tr_style = item.message_read == false ? "font-weight:bold" : "";
      &lt;tr style="@tr_style"&gt;
          &lt;td&gt;
              &lt;input type="checkbox" name="MessageIds" id="MessageIds" value="@item.id"/&gt;
          &lt;/td&gt;
          &lt;td&gt;
              @Html.DisplayFor(modelItem =&gt; item.message_read)
          &lt;/td&gt;
          &lt;td&gt;
              @Html.ActionLink(item.user_sender.username, "Overview", "User", new { username = item.user_sender.username }, null)
          &lt;/td&gt;
          &lt;td&gt;
              @Html.ActionLink(item.subject, "Details", new { id = item.id })
          &lt;/td&gt;
          &lt;td&gt;
              @Html.DisplayFor(modelItem =&gt; item.timestamp)
          &lt;/td&gt;
      &lt;/tr&gt;
  }
  &lt;/table&gt;
  </code></pre>
  
  <p>Notice how I am using this code: username = item.user_sender.username, however, I did NOT include the "user_sender" on the Db Call.</p>
  
  <p>Even without it, this code still works.</p>
  
  <p>So my questions are:</p>
  
  <ol>
  <li><p>Navigation Properties work by calling the DB using a join statement, is that correct?</p></li>
  <li><p>When you use Navigation Properties like item.user_sender.username, is that a separate call to the DB? That would mean that foreach is calling the DB for each item, right?</p></li>
  <li><p>In that code above, am I calling the DB for every foreach item? If I added the .Include("user_reciever").Include("user_sender"), would that mean I won't be calling the Db for every foreach item? (I am guessing no because all the items are already pre-loaded with one db join statement)</p></li>
  <li><p>Is this an effective way to run this code? I wan't to display the user messages that contains the Username from another table. I user Sender_id, Reciever_id to find out who sent it and who recieved it.</p></li>
  </ol>
  
  <p>Thank you for all the help.</p>