Как не отображать нулевые свойства с помощью AutoMapper - PullRequest
0 голосов
/ 17 июня 2020

Я пытаюсь настроить отображение, чтобы убедиться, что нулевое значение не будет отображено. Я использую метод ForAllMembers , но он не работает. (Он работает с методом ForMember ).

Вот мой код:

public void DontMapNullable()
{
    var config = new MapperConfiguration(cfg => {
        cfg.CreateMap<Source, Destination>()
            .ForAllMembers(opt => opt.Condition((src,dst,srcMember) => srcMember != null));
    });

    var mapper = config.CreateMapper();

    Source source = new Source() { SomeInt = null };

    int destInt = 42;
    Destination destination = new Destination() { SomeInt = destInt };

    destination = mapper.Map<Source, Destination>(source, destination);
    Assert.Equal(destInt,destination.SomeInt);
}

public class Source
{
    public int? SomeInt { get; set; } = null;
}

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

Мое утверждение не работает, потому что destination.SomeInt равно 0, а не 42. Я предполагаю эта карта Automapper преобразует null в int и устанавливает свойство назначения равным 0.

...