title: How To Model Aggregates and Persist to Database in DDD
body: <p>I am just trying to get out of my comfort zone of typical N-Tier architecture of Repository/Service/Presentation and have started looking at DDD with Aggregates and I have to admit I'm a little confused and was hoping someone could clarify the following example:</p>
  
  <p>If I had an Entity called News, NewsImage and Customer which were all EF persist-able objects like so:</p>
  
  <pre><code>public class Customer
  {
      public virtual int Id { get; set; }
      public virtual string Name { get; set; }
  }
  
  public class NewsImage
  {
      public virtual int Id { get; set; }
      public virtual byte[] Data { get; set; }
      public virtual News News { get; set; }
  }
  
  public class News
  { 
      public virtual int Id { get; set; }
      public virtual string Name { get; set; }
      public virtual ICollection&lt;NewsImage&gt; NewsImages { get; set; }
      public virtual Customer Customer { get; set; }
  }
  </code></pre>
  
  <p>As I understand it these could be the objects we would use to persist the domain objects to the database but if we are using aggregates from the domain model we could have something like this:</p>
  
  <pre><code>public class NewsAggregate
  {
      public int Id { get; set; }
      public string Name { get; set }
  
      public void AddImageToNews(byte[] imageData)
      {
           // Hide NewsImage or that object and add the byte[] data here?
      }
  }
  </code></pre>
  
  <p>My questions are following and I would appreciate any clarification as I am certain I am misunderstanding the fundamental principles here:</p>
  
  <ol>
  <li>Only the aggregate objects should be exposed to the presentation layer (or any consuming layer).</li>
  <li>How do I handle converting/persisting the aggregate objects to the database, I could use mapping which is fine but then how do I know if I am creating an object or updating (by whether it is transient if the Id is set or not?).  How do I know if new images have been added and which to update or remove?  I think the problem I am having is I call create pass a news aggregate to a Repository and create it, I could then get the aggregate back from the domain populated via the entities with EF and then add an image, when I pass the news aggregate back how do I know what has changed in order to create/update data?
  <ol>
  <li>Where should the customer go, should it be on the news aggregate object as an AddCustomer method, should there be a CustomerAggregate which has an AddNews method and with both of these options how to persist?</li>
  </ol></li>
  </ol>
  
  <p>Many thanks for any insight, I've been reading around and looking at sample projects which demonstrate the concept but don't seem to fully explain best ways to achieve this.</p>