Skip display of null properties

I use AutoMapperto match the ViewModel with the model. However, I want the properties not to be displayed if the corresponding property of the source null.

My source class is as follows:

public class Source
{
    //Other fields...
    public string Id { get; set; } //This should not be mapped if null
}

And destination class:

public class Destination
{
    //Other fields...
    public Guid Id { get; set; }
}

And this is how I configured mapper:

Mapper.Initialize(cfg =>
{
    //Other mappings...
    cfg.CreateMap<Source, Destination>()
        .ForAllMembers(opts => opts.Condition((src, dest, srcMember) => srcMember != null));
});

I thought that mapping would mean that the properties would not be overwritten at the destination if the source code null. But apparently I'm wrong: even when Source.Idnull, it still displays, AutoMapper assigns it an empty Guid ( 00000000-0000-0000-0000-000000000000), overwriting the existing one. How can I tell AutoMapper to skip property mapping if the source is NULL?

. , Guid<->String, automapper, . , Id, null.

+6
1

- Guid.Empty.

    cfg.CreateMap<Source, Destination>()
        .ForAllMembers(opts => opts.Condition((src, dest, srcMember) => ((Guid)srcMember) != Guid.Empty));

- , , , . Guid, , . Guid.Empty. .

+6

Source: https://habr.com/ru/post/1685233/


All Articles