跳过映射null属性

Mas*_*r_T 7 c# automapper

我正在使用AutoMapperViewModel映射到Model.但是,如果相应的source属性是,我希望不映射属性null.

我的源类如下:

public class Source
{
    //Other fields...
    public string Id { get; set; } //This should not be mapped if null
}
Run Code Online (Sandbox Code Playgroud)

目的地类是:

public class Destination
{
    //Other fields...
    public Guid Id { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

这是我配置映射器的方式:

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

我认为映射意味着如果源是属性,则不会在目标中覆盖属性null.但显然我错了:即使Source.Id是null,它仍然被映射,AutoMapper会为它分配一个空的Guid(00000000-0000-0000-0000-000000000000),覆盖现有的.如果源为空,如何正确告诉AutoMapper跳过属性的映射?

注意:我不认为这是Guid<->String转换的问题,这种转换在automapper中工作,我在传递中使用它.问题是,当它为null时,它不会跳过Id属性.

Luc*_*anu 7

简单的方法是不必区分null和Guid.Empty.像这样

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

在这种情况下,源成员不是您映射的字符串值,它是将分配给目标的已解析值.它的类型是Guid,一个结构,所以它永远不会为null.空字符串将映射到Guid.Empty.看到这里.