1

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?

Kayomez
  • 33
  • 5
  • In your code snippet, there is no `Thing1` property of `thing` class. But in unit test result there is shown `Thing1`. Could you post actual code? – kosist Jul 27 '22 at 09:34
  • I updated it, ran the test, and forgot to copy the code over. Fixed it so I hope this is clearer. – Kayomez Jul 27 '22 at 10:05
  • In your sample, you first map from `thing1`, but overwrite the result with a new record when mapping from `thing2`. This is why the old values are lost. By "record class" do you mean a C# immutable record or just a class? – Markus Jul 27 '22 at 10:22

1 Answers1

2

Change your code to this:

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

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

kosist
  • 2,868
  • 2
  • 17
  • 30
  • I do imagine it's something I've done wrong so I'm expecting someone would be able to advise how i should adjust my code in order to make the assert correct. I wouldn't be asking otherwise. Do you understand what it is I'm trying to achieve? – Kayomez Jul 27 '22 at 09:50