当 map 返回 null 时,Automapper 尝试创建对象

当我尝试进行一些自定义映射并且有时将目标属性映射到 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 个参数或只有可选参数的构造函数。参数名称:类型”


鸿蒙传说
浏览 209回答 1
1回答

冉冉说

您可以在PreCondition此处使用 a ,如果不满足指定条件,这将避免映射(甚至尝试解析源值):CreateMap<Source, Destination>()&nbsp; &nbsp; .ForMember(d => d.DropDown, o =>&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; o.PreCondition(src => src.DropDownValues != null);&nbsp; &nbsp; &nbsp; &nbsp; o.MapFrom((src, d) =>&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return new SelectList(src.DropDownValues, src.SelectedValue);&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; });需要这个的原因在这里解释:对于每个属性映射,AutoMapper 会在评估条件之前尝试解析目标值。因此,它需要能够在不抛出异常的情况下执行此操作,即使条件会阻止使用结果值也是如此。
打开App,查看更多内容
随时随地看视频慕课网APP