Value Converters can be used to define conversion scoped to a single map:
public class CurrencyFormatter : IValueConverter<decimal, string> {
public string Convert(decimal source, ResolutionContext context)
=> source.ToString("c");
}
var configuration = new MapperConfiguration(cfg => {
cfg.CreateMap<Order, OrderDto>()
.ForMember(d => d.Amount, opt => opt.ConvertUsing(new CurrencyFormatter()));
cfg.CreateMap<OrderLineItem, OrderLineItemDto>()
.ForMember(d => d.Total, opt => opt.ConvertUsing(new CurrencyFormatter()));
});
Is it possible to rely on the existing collection mapping functionality, but define a Value Converter for the mapping of the collection items?
cfg.CreateMap<OrderLineItem, OrderLineItemDto>()
.ForMember(d => d.TotalCollection, /* what to specify here, so that the individual items mapped are using a converter */);
I know I could specify a Value Converter that handles ICollection<decimal>
to ICollection<string>
or similar, but that's not really elegant (and I also do not want to specify a global type mapping decimal to string).
question from:
https://stackoverflow.com/questions/65835719/how-to-use-value-converters-for-collection-properties-with-automapper 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…