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

冉冉说
TA贡献1877条经验 获得超1个赞
您可以在PreCondition
此处使用 a ,如果不满足指定条件,这将避免映射(甚至尝试解析源值):
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);
});
});
需要这个的原因在这里解释:
对于每个属性映射,AutoMapper 会在评估条件之前尝试解析目标值。因此,它需要能够在不抛出异常的情况下执行此操作,即使条件会阻止使用结果值也是如此。
- 1 回答
- 0 关注
- 208 浏览
添加回答
举报
0/150
提交
取消