title: Entity Framework 4 Code First and the new() Operator
body: <p>I have a rather deep hierarchy of objects that I'm trying to persist with Entity Framework 4, POCO, PI (Persistence Ignorance) and Code First.  Suddenly things started working pretty well when it dawned on me to not use the new() operator.  As originally written, the objects frequently use new() to create child objects.</p>
  
  <p>Instead I'm using my take on the Repository Pattern to create all child objects as needed.  For example, given:</p>
  
  <pre><code>class Adam
  {
    List&lt;Child&gt; children;
    void AddChildGivenInput(string input) { children.Add(new Child(...)); }
  }
  
  class Child
  {
    List&lt;GrandChild&gt; grandchildren;
    void AddGrandChildGivenInput(string input) { grandchildren.Add(new GrandChild(...)); }
  }
  
  class GrandChild
  {
  }
  </code></pre>
  
  <p>("GivenInput" implies some processing not shown here)</p>
  
  <p>I define an <code>AdamRepository</code> like:</p>
  
  <pre><code>class AdamRepository
  {
      Adam Add() 
      { 
          return objectContext.Create&lt;Adam&gt;(); 
      }
      Child AddChildGivenInput(Adam adam, string input) 
      { 
          return adam.children.Add(new Child(...)); 
      }
      GrandChild AddGrandchildGivenInput(Child child, string input) 
      { 
          return child.grandchildren.Add(new GrandChild(...)); 
      }
  }
  </code></pre>
  
  <p>Now, this works well enough.  However, I'm no longer "ignorant" of my persistence mechanism as I have abandoned the new() operator.  </p>
  
  <p>Additionally, I'm at risk of an <a href="http://en.wikipedia.org/wiki/Anemic_Domain_Model" rel="nofollow noreferrer">anemic domain model</a> since so much logic ends up in the repository rather than in the domain objects.</p>
  
  <p><strong>After much adieu, a question:</strong></p>
  
  <p>Or rather several questions...</p>
  
  <ul>
  <li>Is this pattern required to work with EF 4 Code First?</li>
  <li>Is there a way to retain use of new() and still work with EF 4 / POCO / Code First?</li>
  <li>Is there another pattern that would leave logic in the domain object and still work with EF 4 / POCO / Code First?</li>
  <li>Will this restriction be lifted in later versions of Code First support?</li>
  </ul>
  
  <p><em>Sometimes trying to go the POCO /
  Persistence Ignorance route feels like
  swimming upstream, other times it feels
  like swimming up Niagra Falls.  Still, I want to believe...</em></p>