在Automapper中,将对象映射到列表中是否可能?

3

我有一个类名为Foos:

public class Foos
{
    public string TypeName;

    public IEnumerable<int> IDs;
}

能否使用AutoMapper将它映射为Foo对象的IList?

public class Foo
{
    public string TypeName;

    public int ID;
}

3
使用http://valueinjecter.codeplex.com/ 是完全可以实现的,事实上这正是我使用它的其中一个原因。 - Omu
@Omu 我从未见过这个项目... 谢谢! - stacker
1个回答

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

1
为什么不直接发布一个答案,而是在评论中暗示呢? - xr280xr

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接