AutoMapper Map all properties based on other model property value

Viewed 1705

I have the following scenario :

Source class :

   public class Source
    {
      public int? A { get; set; }

      public int? B { get; set; }

      public int? C { get; set; }
    }

Destination class :

 public class Destination
    {
        public int A { get; set; }

        public bool AIsNull { get; set; }

        public int B { get; set; }

        public bool BIsNull { get; set; }

        public int C { get; set; }

        public bool CIsNull { get; set; }
    }

I would like to obtain a mapping from Source => Destion in the following manner as following :

  • try to set the destination property with the associated source property (this it can be done using a Converter( implementing ITypeConverter)
  • after the property is set, I want to set the destination associated IsNull property based on the nullable source property.

EDIT, after some research :

  class Program
{
    static void Main(string[] args)
    {
        var srcClass = new SourceClass { Value1 = 10, Value2 = null, Value3 = 20 };

        Mapper.Initialize(cfg =>
        {
            cfg.ClearPrefixes();
            cfg.RecognizePostfixes("IsNull");
            cfg.CreateMap<SourceClass, TargetClass>();
        });

        var targetClass = Mapper.Map<SourceClass, TargetClass>(srcClass);

    }
}

public class SourceClass
{
    public int? Value1 { get; set; }
    public int? Value2 { get; set; }
    public int? Value3 { get; set; }
}

public class TargetClass
{
    public bool Value1IsNull { get; set; }
    public bool Value2IsNull { get; set; }
    public bool Value3IsNull { get; set; }
}

and still, the magic does not happen for this case

1 Answers

I think something like this should work, I have not tested this in VS so use with a grain of salt.

var map = CreateMap<Source,Target>();

map.ForAllMembers(opt => opt.Ignore());

map.ForMember(dest => dest.A, opt => opt.MapFrom( src => src.A.HasValue ? src.A.Value : 0));

map.ForMember(dest => dest.AIsNull, opt => opt.MapFrom( src => src.A.HasValue ? true : false));
Related