Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
362 views
in Technique[技术] by (71.8m points)

How to use Value Converters for Collection properties with AutoMapper

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...