MapAutomapper ignore Null values

167 views Asked by At

I want to map from a record class to the same record class but ignore null values. I tried using the method found here How to ignore null values for all source members during mapping in Automapper 6? but it hasn't worked.

This is what I've tried:

public class UnitTest1
{
    [Fact]
    public void Test1()
    {
        var config = new MapperConfiguration(cfg =>
        {
            cfg.CreateMap<Thing, Thing>()
                .ForAllMembers(opt => opt.Condition((src, dest, srcMember) => srcMember != null));
        });

        var mapper = config.CreateMapper();
        var thing1 = new Thing() { Thing1 = "start" };
        var thing2 = new Thing() { Thing2 = "hello", Thing3 = "world" };
        var ot = mapper.Map<Thing>(thing1);
        ot = mapper.Map<Thing>(thing2);

        Assert.Equal(new Thing() { Thing1 = "start", Thing2 = "hello", Thing3 = "world" }, ot);
    }
}
record Thing
{
    public string? Thing1 { get; set; }
    public string? Thing2 { get; set; }
    public string? Thing3 { get; set; }
}

enter image description here

Can anyone advise what I should do?

1

There are 1 answers

1
kosist On BEST ANSWER

Change your code to this:

var ot = mapper.Map(thing1, thing2);

so you will define source and target objects, and they will be merged.