【问题标题】:Skip mapping null properties跳过映射空属性
【发布时间】:2018-02-16 07:28:45
【问题描述】:

我正在使用AutoMapper 将 ViewModel 映射到 Model。但是,如果相应的源属性是null,我希望不映射属性。

我的源码类如下:

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

目标类是:

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

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

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

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

注意:我不认为这是Guid&lt;-&gt;String 转换的问题,这种转换在automapper 中有效,我在pass 中使用过。问题是当它为空时它不会跳过 Id 属性。

【问题讨论】:

    标签: c# automapper


    【解决方案1】:

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

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

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

    【讨论】:

    • 嗯...我会尝试的,但我不明白为什么如果我的不行的话这应该有效...我的意思是,如果 srcMember 为空,您的表达式将返回 false.. . 与我的“srcMember != null”检查相同的情况。如果我的不行,你的为什么要工作?
    • 我已经添加了解释。
    • 这很好用,但似乎不适用于ReverseMap()
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-10
    • 1970-01-01
    • 2023-02-11
    相关资源
    最近更新 更多