title: ASP.NET MVC model to viewmodel mapping with additional secondary entities
body: <p>I'm using ASP.NET MVC 3, with Raven DB as a backing data store. I have a set of models, which I'm interested in transforming into ViewModels. To accomplish this, I'm leveraging AutoMapper to take care of the dirty work of mapping each property to the corresponding one in the ViewModel. Let's say that I've got a model like so:</p>
  
  <pre><code>public class FooModel
  {
      public int Id { get; set; }
      public string Name { get; set; }
      public int AlphaId { get; set; }
      public int BetaId { get; set; }
  }
  </code></pre>
  
  <p>And then let's say I want to transform it into a ViewModel like so:</p>
  
  <pre><code>public class FooViewModel
  {
      public int Id { get; set; }
      public string Name { get; set; }
      public int AlphaId { get; set; }
      public Alpha Alpha { get; set; }
      public int BetaId { get; set; }
      public Beta Beta { get; set; }
  }
  </code></pre>
  
  <p>My map is then set up like this at app startup:</p>
  
  <pre><code>Mapper.CreateMap&lt;Foo, FooViewModel&gt;();
  </code></pre>
  
  <p>Then, in the controller I'm performing the map as so:</p>
  
  <pre><code>public ActionResult FooDetails(string id)
  {
      using(var session = this.documentStore.OpenSession())
      {
          var fooInstance = session.Load&lt;Foo&gt;(id);
          var fooViewModel = Mapper.Map&lt;FooViewModel&gt;(fooInstance);
          return this.View(fooViewModel);
      }
  }
  </code></pre>
  
  <p>The problem is that as you can see above, the entity coming out of the repository has 2 properties which are the keys of other objects, of types Alpha and Beta. I'm interested in hydrating Alpha and Beta based upon the AlphaId and BetaId keys. </p>
  
  <p>At first I thought I'd leverage AutoMapper's custom conversion capabilities, but I don't think that will work given that we would need a data session to be injected into the mapping (to call the data store to retrieve the Alpha or Beta object). </p>
  
  <p>The other option is to just do all the work in the controller action, but that quickly gets unwieldy (not in the particular example given, but thats just an example to illustrate the point).</p>
  
  <p>Where should the hydration of Alpha and Beta take place, and what's a good pattern here?</p>