title: Cleanest Way To Map Entity To DTO With Linq Select?
body: <p>I've been trying to come up with a clean and reusable way to map entities to their DTOs.  Here is an example of what I've come up with and where I'm stuck.  </p>
  
  <p><strong>Entities</strong></p>
  
  <pre><code>public class Person
  {
      public int ID { get; set; }
      public string Name { get; set; }
      public Address Address { get; set; }
      // Other properties not included in DTO
  }
  
  public class Address
  {
      public int ID { get; set; }
      public string City { get; set; }
      // Other properties not included in DTO
  }
  </code></pre>
  
  <p><strong>DTOs</strong></p>
  
  <pre><code>public class PersonDTO
  {
      public int ID { get; set; }
      public string Name { get; set; }
      public AddressDTO Address { get; set; }
  }
  
  public class AddressDTO
  {
      public int ID { get; set; }
      public string City { get; set; }
  }
  </code></pre>
  
  <p><strong>Expressions</strong></p>
  
  <p>This is how I began to handle the mapping.  I wanted a solution that wouldn't execute the query before mapping.  I've been told that if you pass a <code>Func&lt;in, out&gt;</code> instead of <code>Expression&lt;Func&lt;in, out&gt;&gt;</code> that it will execute the query before mapping.</p>
  
  <pre><code>public static Expressions
  {
      public static Expression&lt;Func&lt;Person, PersonDTO&gt;&gt; = (person) =&gt; new PersonDTO()
      {
          ID = person.ID,
          Name = person.Name,
          Address = new AddressDTO()
          {
              ID = person.Address.ID,
              City = person.Address.City
          }
      }
  }
  </code></pre>
  
  <p>One issue with this is that I already have an expression that maps an <code>Address</code> to an <code>AddressDTO</code> so I have duplicated code.  This will also break if <code>person.Address</code> is null.  This gets messy very quick especially if I want to display other entities related to person in this same DTO.  It becomes a birds nest of nested mappings.</p>
  
  <p>I've tried the following but Linq doesn't know how to handle it.</p>
  
  <pre><code>public static Expressions
  {
      public static Expression&lt;Func&lt;Person, PersonDTO&gt;&gt; = (person) =&gt; new PersonDTO()
      {
          ID = person.ID,
          Name = person.Name,
          Address = Convert(person.Address)
      }
  
      public static AddressDTO Convert(Address source)
      {
          if (source == null) return null;
          return new AddressDTO()
          {
              ID = source.ID,
              City = source.City
          }
      }
  }
  </code></pre>
  
  <p>Are there any elegant solutions that I'm missing?</p>