是否可以将对象映射到Automapper中的List?

时间:2010-08-02 14:06:14

标签: collections automapper

我有一堂课Foos:

public class Foos
{
    public string TypeName;

    public IEnumerable<int> IDs;
}

是否可以将它与AutoMapper映射到ILoo的Foo对象?

public class Foo
{
    public string TypeName;

    public int ID;
}

1 个答案:

答案 0 :(得分:4)

Omu的回答让我知道如何解决问题(建议+1)。我使用了ConstructUsing()方法,它对我有用:

    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;
        }
    }