繁体   English   中英

AutoMapper:将空源对象映射到十进制

[英]AutoMapper: Map null source object to decimal

我需要将类型为PriceValue的对象映射为十进制值,并且配置了以下映射:

public class PriceValue
{
    public decimal Value { get; set; }
    ...
}

...

Mapper.CreateMap<PriceValue, decimal>()
    .ConvertUsing(src => src.Value);

问题是,当srcnull ,将引发异常。

最好的配置映射的方式是返回default(decimal)

在C#6中,这非常简单:

Mapper.CreateMap<PriceValue, decimal>()
    .ConvertUsing(src => src?.Value ?? default(decimal));

使用ConvertUsing,您可以完全覆盖所有映射配置,因此没有其他选项可用。

我们正在使用类似的类系统,如PriceValue,其中包含int,long等。我们能够针对基类创建通用映射。 这是设置:

public class PriceValue : ValueDecimal
{
    public decimal Value { get; set; }
    ...
}

映射将变为:

Mapper.CreateMap<ValueDecimal, decimal>().ConvertUsing(f => f != null ? f.Value : default(decimal));

如果使用这种方法(具有基类),则可以避免为创建的每个新类设置映射。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM