title: Web Api 2 + EF6 - Building a DTO
body: <p>For a project we are making use of EF and Web Api 2.  To abstract away from our database models we are making use of DTO's. We have a factory to construct these DTO's:</p>
  
  <pre><code>public class FooFactory:IModelConverter&lt;FooDTO, Foo&gt;
  {
  
      public FooDTO Create(Foo data)
      {
          return new FooDTO()
          {
             //Some fields
          };
      }
  }
  </code></pre>
  
  <p>In our Api call we can do:</p>
  
  <pre><code>public async Task&lt;IHttpActionResult&gt; GetFoo()
      {
          var foos = db.Foos
  
          //DO STUFF
  
           var dtos = (await foos.ToListAsync()).Select(m =&gt; _converter.Create(m)); //Converter is an instance of FooFactory)
  
          return Ok(dtos);
      }
  </code></pre>
  
  <p>This works, but implies that, after we execute the query, we have to loop over all our results and convert each model to a DTO.</p>
  
  <p>On the other hand, we could do:</p>
  
  <pre><code>public async Task&lt;IHttpActionResult&gt; GetFoo()
      {
          var foos = db.Foos
  
          //DO STUFF
  
          return Ok(await foos.Select(m =&gt; new FooDTO() { 
              //Assign fields
          }).ToListAsync());
      }
  </code></pre>
  
  <p>Which would integrate this projection into the query executed by EF. But this exposes all the inner details of the FooDTO and we have to repeat all this creation code.</p>
  
  <p>Is there a way to do something like:</p>
  
  <pre><code>public async Task&lt;IHttpActionResult&gt; GetFoo()
      {
          var foos = db.Foos
  
          //DO STUFF
  
          return Ok(await foos.Select(m =&gt; _converter.Create(m)).ToListAsync());
      }
  </code></pre>
  
  <p>which does not work, because Linq to Entities can't deal with the create function.</p>
  
  <p>I'm also open to alternative ways to work with DTO's, is there a better way to do this, or is there no way to avoid the extra pass through all query results?</p>
  
  <p>Oh, the catch, I want to do this <strong>without</strong> automapper.</p>