Automapper 5 - 将Nullable <t>映射到具有条件的T

时间:2016-08-05 09:19:29

标签: c# automapper

我想将Nullable<T>映射到T,但前提是源值不是null。在null的情况下,我想保留目标值。所以我使用.ForAllMembers(opt => opt.Condition((src, dst, srcVal, dstVal) => srcVal != null))设置了映射。这适用于string等参考类型,但不适用于Nullable<T>。如果类型int?的源值为null,则条件中的srcVal0。因此,将返回true并覆盖目标值。

当值为Nullable<T>时,如何阻止null类型属性的映射?

以下是代码:

public class Program
{
    public static void Main(string[] args)
    {
        MapperConfigurationExpression mce = new MapperConfigurationExpression();
        mce.CreateMap<Src, Dst>()
           .ForAllMembers(opt => opt.Condition((src, dst, srcVal, dstVal) => srcVal != null));
        MapperConfiguration configuration = new MapperConfiguration(mce);
        configuration.AssertConfigurationIsValid();
        IMapper mapper = new Mapper(configuration);

        Src s = new Src();
        Dst d = mapper.Map<Dst>(s);

        Console.WriteLine($"Text: {d.Text}, Int: {d.Int}, Short: {d.Short}");
    }
}

public class Src
{
    public string Text { get; set; }
    public int? Int { get; set; }
    public short? Short { get; set; }
}

public class Dst
{
    Dst()
    {
        Text = "Default";
        Int = 300;
        Short = 10;
    }

    public string Text { get; set; }
    public int Int { get; set; }
    public short Short { get; set; }
}

0 个答案:

没有答案