Skip mapping null properties

允我心安 提交于 2020-06-25 09:42:53

问题


I'm using AutoMapper to map a ViewModel to a Model. However, I want properties to not be mapped if the corresponding source property is 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 the destination class is:

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

And here is how I configured the 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 properties don't get overwritten in the destination if the source one is null. But apparently I'm wrong: even when Source.Id is null, it still gets mapped, AutoMapper assigns it an empty Guid (00000000-0000-0000-0000-000000000000), overwriting the existing one. How do I properly tell AutoMapper to skip mapping of a property if the source is null?

NOTE: I don't think this is a problem with the Guid<->String conversion, such conversion works in automapper, I've used it in the pass. The problem is that it's not skipping the Id property when it is null.


回答1:


The easy way would be to not have to distinguish between null and Guid.Empty. Like this

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

In this case the source member is not the string value you map from, it's the resolved value that would be assigned to the destination. It's of type Guid, a struct, so it will never be null. A null string will map to Guid.Empty. See here.



来源:https://stackoverflow.com/questions/46098376/skip-mapping-null-properties

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!