title: Domain-Driven Design with Entity Framework & Repository Pattern
body: <p>I used to deal with simple apps that have <em>Service Layer</em> containing all of the business logic. In <em>Domain Driven Design</em> it's common to keep business logic in a rich model.</p>
  
  <p>Watched a tutorial by Pluralsight in which they mention <em>Repositories</em> and noticed that a repo normally contains basic CRUD operations (create, update, fetch &amp; remove entity). Nothing much was explained with regard to <em>Entity Framework</em>.</p>
  
  <p><em>Entity Framework 6</em> &amp; <em>Entity Framework Core</em> already provide <em>Repository/UoW</em> out of the box. <strong>I'm wondering if we can omit creating Repository Layer in this case?</strong></p>
  
  <p><em>So, how I imagine the app without a separate Repository layer...</em></p>
  
  <p>My understanding is:</p>
  
  <p>For example we have <code>Customer</code> model as an Aggregate Root (rich domain model). And that model has one-to-many relation <code>ICollection&lt;Payment&gt; Payments</code>. Plus, according to DDD - we keep our logic inside the model - so we have <code>MakePayment</code> method.</p>
  
  <p>The code will be as follows:</p>
  
  <pre><code>public class Customer
  {
      public virtual ICollection&lt;Payment&gt; Payments { get; set; }
  
      // ... other properties/collections
  
      public void MakePayment(decimal amount)
      {
          this.Payments.Add(new Payment() { Amount = amount });
      }
  }
  </code></pre>
  
  <p>With <em>Entity Framework</em> we can <strong>eagerly load</strong> the entire tree with the result <code>Customer</code> already has all their <code>Payments</code> mapped.</p>
  
  <p><em>(say, we deal with an ASP.NET WebAPI app)</em></p>
  
  <p>So, in order to make a payment, I imagine, we do the following:</p>
  
  <ol>
  <li><p>in our controller / service we fetch a customer (for example by <code>id</code>)</p></li>
  <li><p>then follows the code <code>customer.MakePayment(10);</code></p></li>
  <li><p>after that we call <code>dbContext.SaveChanges()</code> method</p></li>
  <li><p><code>DbContext</code> tracks the changes and stores the payment - <em>Bingo!</em></p></li>
  </ol>
  
  <p><strong>Is my understanding correct?</strong></p>
  
  <hr>
  
  <p>Regarding Service Layer:</p>
  
  <p><strong>Would it be okay to have Service Layer with DDD in such a web app?</strong> </p>
  
  <p><em>I still think keeping the code in controller isn't necessarily the right thing to do (even with DDD) as long as e.g. part of functionality MAY BE required in a WPF app - so we can use Service Layer with it.</em></p>
  
  <p><em>Seems like the most optimal approach, doesn't it?</em></p>