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