Automapper: Handling Nullable Properties for Object To Object Mapping

1k views Asked by At

I am using Automapper 6.0.2. I have a console application with the following code below. I am trying to achieve a sort or partial update feature by placing a condition for the object to object mapping relationship. So I am using:

.ForAllMembers(opt => opt.Condition(
   (source, destination, sourceMember, destMember) => sourceMember != null))

However it seems Automapper recreates the nullable object properties as non nullable forms with default values during the mapping Mapper.Map(newViewModel, newModel). I would expect that in the code below newModel stays unchanged.

Expected Object

enter image description here

But I Get

enter image description here

How do I get around this? If I check for default DateTime and int values, I will be constrained to using values above 0 for the int property. I need to check for null not default values

public class Program
{
    public static void Main(string[] args)
    {
        Mapper.Initialize(config =>
        {
            config.CreateMap<ViewModel,Model>().ForAllMembers(opt => opt.Condition(
               (source, destination, sourceMember, destMember) => sourceMember != null));
        });


        var newModel = new Model
        {
            Name = "My Name",
            Age = 18,
            DateOfBirth = new DateTime(2000, 1, 1)
        };

        var newViewModel = new ViewModel();

        //Nulls should be ignored while mapping
        Mapper.Map(newViewModel, newModel);
    }
}

public class Model
{
    public string Name { get; set; }
    public int Age { get; set; }
    public DateTime DateOfBirth { get; set; }
}
public class ViewModel
{
    public string Name { get; set; }
    public int? Age { get; set; }

    public DateTime? DateOfBirth { get; set; }
}
1

There are 1 answers

1
WhileTrueSleep On

just correct your mapping as followed

 config.CreateMap<Model, ViewModel>().ForAllMembers(opt => opt.Condition(
               (source, destination, sourceMember, destMember) => sourceMember != null));

and your mapper use source first then target

Mapper.Map(newModel, newViewModel);