开发者

AutoMapper using operation to populate destination

开发者 https://www.devze.com 2023-02-10 08:58 出处:网络
I need to map a list from destination object to source, using a public method on the source o开发者_StackOverflow中文版bject.

I need to map a list from destination object to source, using a public method on the source o开发者_StackOverflow中文版bject.

e.g.

public class Destination
{
    private IList<int> List = new List<int>();
    public void Add(int i) { List.Add(i); }
}

public class Source
{
    public int[] List { get; set; }
}

So in pseudo-pseudo language the mapping should be: Mapper.CreateMap foreach item in Source.List, invoke Source.Add(item)

Can this be done?


Yes. Use the ConvertUsing syntax:

Mapper.CreateMap<Source, Destination>()
    .ConvertUsing(s =>
                    {
                        var d = new Destination();
                        foreach(var i in s.List)
                        {
                            d.Add(i);
                        }
                        return d;
                    });


I don't think so.

AutoMapper custom type converters accept only source and they return destination.

But, why don't you just implement an implicit type conversion from int[] to Destination? http://www.csharphelp.com/2006/10/type-conversion-and-conversion-operators-in-c/

0

精彩评论

暂无评论...
验证码 换一张
取 消