Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/339.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 当映射返回null时,自动映射尝试创建对象_C#_Automapper - Fatal编程技术网

C# 当映射返回null时,自动映射尝试创建对象

C# 当映射返回null时,自动映射尝试创建对象,c#,automapper,C#,Automapper,当我尝试进行一些自定义映射,有时将目标属性映射为null时,Automapper会在尝试创建目标属性对象时抛出异常 我已将一个简化项目上传到github,以演示: 这始于我从Automapper 6升级到8 如果我返回一个新的up对象而不是null,它就可以正常工作,但在这些情况下,我的应用程序希望该值为null 我还确认,每次调用映射时都会命中映射内的断点,以确保没有编译的执行计划 public class Source { public IEnumerable<string&

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

我已将一个简化项目上传到github,以演示:

这始于我从Automapper 6升级到8

如果我返回一个新的up对象而不是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个参数或仅可选参数的构造函数。参数名称:type

您可以在此处使用,这将避免映射,甚至在不满足指定条件时尝试解析源值:

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都会尝试解析 评估条件之前的目标值。所以它必须是 即使条件 将阻止使用结果值