4

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; }
}
Ilya Chumakov
  • 23,161
  • 9
  • 86
  • 114
flexxxit
  • 2,440
  • 5
  • 42
  • 69

1 Answers1

0

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);
WhileTrueSleep
  • 1,524
  • 1
  • 19
  • 32
  • 1
    Nope that is not what i want to do. I am mapping from a viewmodel which can be null to a model in order to update the model values. So in order to get `partial updates`. i need to ignore nulls from the viewmodel object. You have just turned things other way round – flexxxit Apr 28 '17 at 12:28