Can I map an object to a List in Automapper?

I have a Foos class:

public class Foos
{
    public string TypeName;

    public IEnumerable<int> IDs;
}

Can I match it with AutoMapper with IList objects from Foo?

public class Foo
{
    public string TypeName;

    public int ID;
}
+3
source share
1 answer

The answer to ohm gave me an idea how to solve the problem (+1 for suggestion). I used the ConstructUsing () method and 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;
        }
    }
+4
source

Source: https://habr.com/ru/post/1757665/


All Articles