【问题标题】:Automapper attempts to create object when map returns null当 map 返回 null 时,Automapper 尝试创建对象
【发布时间】:2019-08-31 02:06:36
【问题描述】:

当我尝试进行一些自定义映射并且有时将目标属性映射为 null 时,Automapper 会抛出异常以尝试创建目标属性对象。

我已经将一个简化的项目上传到 github 来演示: https://github.com/dreing1130/AutoMapper_Investigation

这开始于我从 Automapper 6 升级到 8 时。

如果我返回一个新的对象而不是 null 它工作正常(我的应用程序希望在这些情况下该值为 null)

我还确认每次调用映射时都会命中我的映射中的断点,以确保没有编译的执行计划

public class Source
{
    public IEnumerable<string> DropDownValues { get; set; }
    public string SelectedValue { get; set; }
}

public class Destination
{
    public SelectList DropDown { get; set; }
}

CreateMap<Source, Destination>()
        .ForMember(d => d.DropDown, o => o.MapFrom((src, d) =>
        {
            return src.DropDownValues != null
                ? new SelectList(src.DropDownValues,
                    src.SelectedValue)
                : null;
        }));

预期结果:当 Source.DropdownValues 为 null 时,Destination.DropDown 为 null

实际结果:抛出异常

"System.Web.Mvc.SelectList 需要有一个 0 args 或只有可选 args 的构造函数。参数名称:类型"

【问题讨论】:

    标签: c# automapper


    【解决方案1】:

    您可以在此处使用PreCondition,如果不满足指定条件,它将避免映射(甚至尝试解析源值):

    CreateMap<Source, Destination>()
        .ForMember(d => d.DropDown, o =>
        {
            o.PreCondition(src => src.DropDownValues != null);
            o.MapFrom((src, d) =>
            {
                return new SelectList(src.DropDownValues, src.SelectedValue);
            });
        });
    

    需要这个的原因解释here

    对于每个属性映射,AutoMapper 尝试解析 评估条件之前的目标值。所以它需要 能够做到这一点而不会抛出异常,即使条件 将阻止使用结果值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-06
      • 1970-01-01
      • 2012-04-24
      • 1970-01-01
      • 2018-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多