title: MVC ViewModels and Entity Framework queries
body: <p>I am new to both MVC and Entity Framework and I have a question about the right/preferred way to do this.</p>
  
  <p>I have sort of been following the Nerd Dinner MVC application for how I am writing this application. I have a page that has data from a few different places. It shows details that come from a few different tables and also has a dropdown list from a lookup table.</p>
  
  <p>I created a ViewModel class that contains all of this information:</p>
  
  <pre><code>class DetailsViewModel {
      public List&lt;Foo&gt; DropdownListData { get; set; }
  
      // comes from table 1
      public string Property1 { get; set; } 
      public string Property2 { get; set; }
  
      public Bar SomeBarObject { get; set; } // comes from table 2
  }
  </code></pre>
  
  <p>In the Nerd Dinner code, their examples is a little too simplistic. The DinnerFormViewModel takes in a single entity: Dinner. Based on the Dinner it creates a SelectList for the countries based on the dinners location.</p>
  
  <p>Because of the simplicity, their data access code is also pretty simple. He has a simple DinnerRepository with a method called GetDinner(). In his action methods he can do simple things like:</p>
  
  <pre><code>Dinner dinner = new Dinner();
  
  // return the view model
  return View(new DinnerFormViewModel(dinner));
  </code></pre>
  
  <p>OR</p>
  
  <pre><code>Dinner dinner = repository.GetDinner(id);
  
  return View(new DinnerFormViewModel(dinner));
  </code></pre>
  
  <p>My query is a lot more complex than this, pulling from multiple tables...creating an anonymous type:</p>
  
  <pre><code>var query = from a in ctx.Table1
              where a.Id == id
              select new { a.Property1, a.Property2, a.Foo, a.Bar };
  </code></pre>
  
  <p>My question is as follows:</p>
  
  <p><strong>What should my repository class look like?</strong> Should the repository class return the ViewModel itself? That doesn't seem like the right way to do things, since the ViewModel sort of implies it is being used in a view. Since my query is returning an anonymous object, how do I return that from my repository so I can construct the ViewModel in my controller actions?</p>