title: How to display data from multiple table in list view asp.net MVC 5 or 6 using viewModel
body: <p>How can I achieve the same result using my view Model</p>
  
  <pre><code>Model 1:
  
  public class Unit
  {
      public int Id { get; set; }
      [Required]
      public string UnitName { get; set; }
  
      public virtual ICollection&lt;Staff&gt; Staffs { get; set; }
  }
  </code></pre>
  
  <p>Model 2:</p>
  
  <pre><code>public class Staff
  {
      public int Id { get; set; }
  
  
      public string FullName { get; set; }
      public int UnitId { get; set; }
      public virtual Unit Unit { get; set; }
  }
  </code></pre>
  
  <p>My ViewModel:</p>
  
  <pre><code>public class StaffVM
  {
      public int Id { get; set; }
      public string FullName { get; set; }
      public int UnitId { get; set; }
      public string UnitName { get; set; }
  }
  </code></pre>
  
  <p>Controller Index function:</p>
  
  <pre><code>    // GET: Staffs
      public ActionResult Index()
      {
  
          var query = from c in db.MyStaff
                      join d in db.MyUnit on c.UnitId equals d.Id
                      select new StaffVM
                      {
                          Id = c.Id,
                          FullName = c.FullName,
                          UnitName = d.UnitName
                      };
          ViewBag.query = query;
  
          return View();
  
      }
  </code></pre>
  
  <p>My View Index view:</p>
  
  <pre><code>@model IEnumerable&lt;MVC5WAuth.ViewModels.StaffVM&gt;
  
  @{
      ViewBag.Title = "Index";
   }
  
  &lt;h2&gt;Index&lt;/h2&gt;
  
  &lt;p&gt;
      @Html.ActionLink("Create New", "Create")
  &lt;/p&gt;
  &lt;table class="table"&gt;
      &lt;tr&gt;
          &lt;th&gt;
              @Html.DisplayNameFor(model =&gt; model.FullName)
          &lt;/th&gt;
          &lt;th&gt;
             Unit
          &lt;/th&gt;
          &lt;th&gt;&lt;/th&gt;
      &lt;/tr&gt;
  
  @foreach (var item in ViewBag.query) {
      &lt;tr&gt;
          &lt;td&gt;
             @item.FullName
         &lt;/td&gt;
         &lt;td&gt;
             @item.UnitName
         &lt;/td&gt;
         &lt;td&gt;
             @Html.ActionLink("Edit", "Edit", new { id=item.Id }) |
             @Html.ActionLink("Details", "Details", new { id=item.Id }) |
             @Html.ActionLink("Delete", "Delete", new { id=item.Id })
         &lt;/td&gt;
     &lt;/tr&gt;
  }
  
  &lt;/table&gt;
  </code></pre>