How to map a nullable property to a DTO using AutoMapper?

I think you may be able to solve this problem simply.

Consider the following example:

public class A 
{
    public int? Foo { get; set; }
    public MyEnum? MyEnum { get; set; }
}

public class B 
{
    public string Bar { get; set; }
    public string MyEnumString { get; set; }
}

The following mapping statement will resolve them as desired:

Mapper.CreateMap<A, B>()
      .ForMember(dest => dest.Bar, opt => opt.MapFrom(src 
        => src.Foo.HasValue ? src.Foo.Value.ToString() : string.Empty))
      .ForMember(dest => dest.MyEnumString, opt => opt.MapFrom(src 
        => src.MyEnum.HasValue ? src.MyEnum.Value.ToString() : string.Empty));

There is no need for a ValueResolver in this case, since your behavior is very simple - empty string if there's no value, or the value if it exists. Instead of calling .ToString(), you can substitute your StringConvert() method. The important thing here is to make use of the .HasValue property on the Nullable<T> wrapper, and to access to .Value property when it exists. This avoids the complication of needing to convert from int? to int.

For converting your persisted string value back into an enum, I encourage you to explore this question: Convert a string to an enum in C# You should be able to use the same mapping logic.

Here is a .NET Fiddle with more detail: https://dotnetfiddle.net/Eq0lof


You can use NullSubstitute to provide alternative value to your destination property if the source property value is null

var config = new MapperConfiguration(cfg => cfg.CreateMap<Person, PersonDto>()
    .ForMember(destination => destination.Name, opt => opt.NullSubstitute(string.Empty)));

var source = new Person { Name = null };
var mapper = config.CreateMapper();
var dest = mapper.Map<Person , PersonDto>(source);