title: How do I handle persistence and unit of work in DDD using Entity Framework?
body: <p>I'm a little overwhelmed with all of the information on DDD, unit of work, domain services, app services, etc. I'm trying to figure out how a persistence-ignorant domain model ultimately gets persisted, specifically in the context of unit-of-work and Entity Framework. Let's say I have an Order aggregate root, which I am attempting to keep in my persistence-ignorant domain model (the core of my architectural onion):</p>
  
  <pre><code>public class Order : EntityBase
  {
      public int Id { get; private set; }
      public int MarketplaceId { get; private set; }
      public int CustomerId {get; set;}
      public List&lt;OrderItem&gt; Items { get; private set; }
      public List&lt;OrderComment&gt; Comments { get; private set; }
  
      public void AddItem(OrderItem item) { /**add item**/ }
      public void AddComment(OrderComment comment) { /**add comment**/ }
      public override bool Validate() { /**validate**/ }
      public void Cancel() { /**cancel**/ }
  }
  </code></pre>
  
  <p>Let's say I have a process that updates a property on the Order entity, for example it changes the CustomerId associated with the order.</p>
  
  <p>I have an IOrderRepository in my domain layer, which would have an implementation (in an outer layer) with a function like this:</p>
  
  <pre><code>Order GetOrder(int orderId)
  {
      //get entity framework order, items, etc.
      //map to domain-layer order and return domain-layer order
  }
  
  void UpdateOrder(Order order)
  {
      //get ENTITY FRAMEWORK order, order items, order comments, etc.
      //take DOMAIN order (passed in to this function), and update EF items fetched above
      //use a single EF unit of work to commit these changes
  }
  </code></pre>
  
  <p>There's something wrong with my approach. The UpdateOrder function seems heavy for a small change; but it also seems I have to do that if my repository isn't aware of which items on the persistence-ignorant domain model have changed. Should I be handling every type of update in a separate repository function? UpdateMarketplace(int marketplaceId), UpdateCustomer(int customerId)?</p>
  
  <p>As I'm typing this, I'm also wondering...maybe the way I have it above is not too heavy? If I change one property, even though I'm doing all of the above, perhaps Entity Framework will recognize that the values being assigned are the same and will only send the one db column update to SQL?</p>
  
  <p><strong>How can I take my Order domain model (fetching is straightforward enough), perform some operation or operations on it that may be limited in scope, and then persist the model using Entity Framework?</strong></p>