Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to map object to a List in Automapper?

I have a class Foos:

public class Foos
{
    public string TypeName;

    public IEnumerable<int> IDs;
}

Is it possible to map it with AutoMapper to IList of Foo objects?

public class Foo
{
    public string TypeName;

    public int ID;
}
like image 1000
Wojciech Markowski Avatar asked Jan 01 '26 22:01

Wojciech Markowski


1 Answers

Omu's answer gaved me an idea how to solve the problem (+1 for suggestion). I've used ConstructUsing() method and it worked for me:

    private class MyProfile : Profile
    {
        protected override void Configure()
        {
            CreateMap<Foos, Foo>()
                .ForMember(dest => dest.ID, opt => opt.Ignore());
            CreateMap<Foos, IList<Foo>>()
                .ConstructUsing(x => x.IDs.Select(y => CreateFoo(x, y)).ToList());                
        }

        private Foo CreateFoo(Foos foos, int id)
        {
            var foo = Mapper.Map<Foos, Foo>(foos);
            foo.ID = id;
            return foo;
        }
    }
like image 136
Wojciech Markowski Avatar answered Jan 05 '26 05:01

Wojciech Markowski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!