title: Projection of single entities in EF with extension methods
body: <p>I like to do projection from my entity models into my view models using extension methods. This means I dont over/under fetch for my models and it makes the code nice and readable. It makes sense that sometimes the projections may include nested models, and I want to get reuse on those sub-projections.</p>
  
  <p>I want to be able to do something like the following:</p>
  
  <pre><code>ctx.People.FiltersAndThings().ToViewModels();//the project my DB Models into view models
  </code></pre>
  
  <p>Extension methods for actual projection</p>
  
  <pre><code>public static IQueryable&lt;PersonModel&gt; ToViewModels(this IQueryable&lt;Person&gt; entities)
  {
      return entities.Select(x =&gt; new PersonModel {
          Me = x.Me.ToViewModel(), //this method cannot be translated into a store expression
          Friends = x.Friends.AsQueryable().ToViewModels() //works fine with some magic (tm)
      });
  }
  
  public static IQueryable&lt;ProfileModel&gt; ToViewModels(this IQueryable&lt;Profile&gt; entities)
  {
      return entities.Select(x =&gt; new ProfileModel { Name = x.Name });
  }
  
  
  public static ProfileModel ToViewModel(this Profile entity)
  {
      return new ProfileModel { Name = entity.Name };
  }
  </code></pre>
  
  <p>When using a Queryable (eg <code>Friends = x.Friends.AsQueryable().ToViewModels()</code>) we can use some magic to flatten this to an expression (see <a href="https://stackoverflow.com/a/10726256/1070291">https://stackoverflow.com/a/10726256/1070291</a>, answer by @LordTerabyte) But when we are doing an assignment with a new clause (eg <code>Me = new ProfileModel { Name = x.Me.Name }</code>) its not an expression so if we bundle this under an extension method (eg <code>Me = x.Me.ToViewModel()</code>) we can't flatten this to an expression. </p>
  
  <p><strong>How does an assignment to a new object work under the scenes in EF?</strong></p>
  
  <p><strong>Is there a way to do convertion to a new object via an extension method?</strong></p>
  
  <p>Full demo code here: <a href="https://github.com/lukemcgregor/ExtensionMethodProjection" rel="nofollow noreferrer">https://github.com/lukemcgregor/ExtensionMethodProjection</a></p>
  
  <p><strong>Edit:</strong></p>
  
  <p>I now have a blog post (<a href="http://blog.staticvoid.co.nz/2016/10/24/composable_repositories_-_nesting_extensions" rel="nofollow noreferrer">Composable Repositories - Nesting Extensions</a>) and <a href="https://www.nuget.org/packages/LinqExpander/" rel="nofollow noreferrer">nuget package</a> to help with nesting extension methods in linq</p>