title: How to map a nullable property to a DTO using AutoMapper?
body: <p>I'm developing an Azure Mobile Service, in my model some of the relationships are optional, making the properties that represent it to be nullable.</p>
  
  <p>For example, my Message entity in my model class is like this:</p>
  
  <pre><code>public partial class Message
  {
      public Message()
      {
          this.Messages = new HashSet&lt;Message&gt;();
      }
  
      public int Id { get; set; }
      public int CreatedById { get; set; }
      public int RecipientId { get; set; }
      public Nullable&lt;int&gt; ParentId { get; set; }
      public string Title { get; set; }
      public string Content { get; set; }
      public int MessageTypeId { get; set; }
      public Nullable&lt;MessageType&gt; Type { get; set; }
      public Nullable&lt;bool&gt; Draft { get; set; }
      public Nullable&lt;bool&gt; Read { get; set; }
      public Nullable&lt;bool&gt; Replied { get; set; }
      public Nullable&lt;bool&gt; isDeleted { get; set; }
  
      [JsonIgnore]
      [ForeignKey("CreatedById")]
      public virtual User CreatedBy { get; set; }
      [JsonIgnore]
      [ForeignKey("RecipientId")]
      public virtual User Recipient { get; set; }
      [JsonIgnore]
      public virtual ICollection&lt;Message&gt; Messages { get; set; }
      [JsonIgnore]
      public virtual Message Parent { get; set; }
  }
  </code></pre>
  
  <p>And my DTO for it looks like this:</p>
  
  <pre><code>public class MessageDTO : EntityData 
  {
      public string CreatedById { get; set; }
      public string RecipientId { get; set; }
      public string ParentId { get; set; }
      public string Title { get; set; }
      public string Content { get; set; }
      public string Type { get; set; }
      public Nullable&lt;bool&gt; Draft { get; set; }
      public Nullable&lt;bool&gt; Read { get; set; }
      public Nullable&lt;bool&gt; Replied { get; set; }
      public Nullable&lt;bool&gt; isDeleted { get; set; }
  
  }
  </code></pre>
  
  <p>In my AutoMapper configuration I have this:</p>
  
  <pre><code>        /*
           * Mapping for Message entity
           */
          cfg.CreateMap&lt;Message, MessageDTO&gt;()
              .ForMember(messageDTO =&gt; messageDTO.Id, map =&gt; 
              map.MapFrom(message =&gt; MySqlFuncs.LTRIM(MySqlFuncs.StringConvert(message.Id))))
              .ForMember(messageDTO =&gt; messageDTO.ParentId, map =&gt; 
              map.MapFrom(message =&gt; message.ParentId))
              .ForMember(messageDTO =&gt; messageDTO.CreatedById, map =&gt; 
              map.MapFrom(message =&gt; MySqlFuncs.LTRIM(MySqlFuncs.StringConvert(message.CreatedById))))
              .ForMember(messageDTO =&gt; messageDTO.RecipientId, map =&gt; 
              map.MapFrom(message =&gt; MySqlFuncs.LTRIM(MySqlFuncs.StringConvert(message.RecipientId))))
              .ForMember(messageDTO =&gt; messageDTO.Type, map =&gt; 
              map.MapFrom(message =&gt; Enum.GetName(typeof(MessageType), message.MessageTypeId)));
  
          cfg.CreateMap&lt;MessageDTO, Message&gt;()
              .ForMember(message =&gt; message.Id, map =&gt; 
              map.MapFrom(messageDTO =&gt; MySqlFuncs.IntParse(messageDTO.Id)))
              .ForMember(message =&gt; message.ParentId, map =&gt; 
              map.MapFrom(messageDTO =&gt; messageDTO.ParentId))
              .ForMember(message =&gt; message.CreatedById, map =&gt; 
              map.MapFrom(messageDTO =&gt; MySqlFuncs.IntParse(messageDTO.CreatedById)))
              .ForMember(message =&gt; message.RecipientId, map =&gt; 
              map.MapFrom(messageDTO =&gt; MySqlFuncs.IntParse(messageDTO.RecipientId)));
  </code></pre>
  
  <p>For reference, the MySqlFuncs class has this functions to handle the conversion from string to int and int to string:</p>
  
  <pre><code>class MySqlFuncs
  {
      [DbFunction("SqlServer", "STR")]
      public static string StringConvert(int number)
      {
          return number.ToString();
      }
      [DbFunction("SqlServer", "LTRIM")]
      public static string LTRIM(string s)
      {
          return s == null ? null : s.TrimStart();
      }
      // Can only be used locally.
      public static int IntParse(string s)
      {
          int ret;
          int.TryParse(s, out ret);
          return ret;
      }
  }
  </code></pre>
  
  <p>While I'm able to insert elements, I'm not able to get them due to the following error:</p>
  
  <blockquote>
    <p>Missing map from Nullable`1 to String. Create using
    Mapper.CreateMap&#60;Nullable`1, String&#62;</p>
  </blockquote>
  
  <p>From this I get that the line resonsible for this error in my AutoMapper definition is:</p>
  
  <pre><code>            .ForMember(messageDTO =&gt; messageDTO.ParentId, map =&gt; 
              map.MapFrom(message =&gt; message.ParentId))
  </code></pre>
  
  <p>AutoMapper needs to know how to map the nullable int from the ParentId property into the DTO. I tried to use the functions from MySqlFuncs class:</p>
  
  <pre><code>            .ForMember(messageDTO =&gt; messageDTO.ParentId, map =&gt; 
              map.MapFrom(message =&gt; MySqlFuncs.LTRIM(MySqlFuncs.StringConvert(message.ParentId))))
  </code></pre>
  
  <p>But that gives shows the error:</p>
  
  <blockquote>
    <p>cannot convert from 'int?' to 'int'</p>
  </blockquote>
  
  <p>If we consider the configuration must be done in a way LINQ can read an convert it correctly, how can I define the mapping so any nullable properties get mapped into string as empty string "" or just the value null into my DTO?</p>
  
  <h2>EDIT 1</h2>
  
  <p>It seems for this to be resolved I have to use a ValueResolver, which I coded as follows:</p>
  
  <pre><code>public class NullableIntToStringResolver : ValueResolver&lt;int?, string&gt;
  {
      protected override string ResolveCore(int? source)
      {
          return !source.HasValue ? "" : MySqlFuncs.LTRIM(MySqlFuncs.StringConvert(source));
      }
  }
  </code></pre>
  
  <p>And changed the mapping to this:</p>
  
  <pre><code>cfg.CreateMap&lt;Message, MessageDTO&gt;()
       .ForMember(messageDTO =&gt; messageDTO.ParentId, 
       map =&gt; map.ResolveUsing(
          new NullableIntToStringResolver()).FromMember(message =&gt; message.ParentId))
  </code></pre>
  
  <p>But this is giving me the error </p>
  
  <blockquote>
    <p>Object reference not set to an instance of an object</p>
  </blockquote>
  
  <p>And the StackTrace is this:</p>
  
  <blockquote>
    <p>at
    AutoMapper.QueryableExtensions.Extensions.ResolveExpression(PropertyMap
    propertyMap, Type currentType, Expression instanceParameter)<br>
    at AutoMapper.QueryableExtensions.Extensions.CreateMemberBindings(IMappingEngine
    mappingEngine, TypePair typePair, TypeMap typeMap, Expression
    instanceParameter, IDictionary`2 typePairCount)<br>
    at AutoMapper.QueryableExtensions.Extensions.CreateMapExpression(IMappingEngine
    mappingEngine, TypePair typePair, Expression instanceParameter,
    IDictionary`2 typePairCount)<br>
    at AutoMapper.QueryableExtensions.Extensions.CreateMapExpression(IMappingEngine
    mappingEngine, TypePair typePair, IDictionary`2 typePairCount)<br>
    at AutoMapper.QueryableExtensions.Extensions.&lt;>c__DisplayClass1`2.b__0(TypePair
    tp)<br>
    at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey
    key, Func`2 valueFactory)<br>
    at AutoMapper.Internal.DictionaryFactoryOverride.ConcurrentDictionaryImpl`2.GetOrAdd(TKey
    key, Func`2 valueFactory)<br>
    at AutoMapper.QueryableExtensions.Extensions.CreateMapExpression[TSource,TDestination](IMappingEngine
    mappingEngine)<br>
    at AutoMapper.QueryableExtensions.ProjectionExpression`1.ToTResult<br>
    at
    Microsoft.WindowsAzure.Mobile.Service.MappedEntityDomainManager`2.Query()
    at Microsoft.WindowsAzure.Mobile.Service.TableController`1.Query()</p>
  </blockquote>
  
  <p>Any idea why I'm getting a null reference?</p>
  
  <h3>Note</h3>
  
  <p>When debugging the error is thrown in my TableController class in the <code>GetAllMessageDTO</code> method:</p>
  
  <pre><code>public class MessageController : TableController&lt;MessageDTO&gt;
  {
      .
      .
      .
      // GET tables/Message
      public IQueryable&lt;MessageDTO&gt; GetAllMessageDTO()
      {
          return Query(); // Error is triggering here
      }
      .
      .
      .
  }
  </code></pre>
  
  <p>When debugging none of the lines of the mapping are accessed when this error happens, since the mapping is done when the service is initialized as far as I can see.</p>