Map a property to a collection item

左心房为你撑大大i 提交于 2019-12-17 22:47:11

问题


I've been sifting through AutoMapper documentation to try and find a recommended solution to this but haven't been able to find it.

Let's say I have a class like the following

public class Foo
{
    public string Note { get; set; }
}

this class gets populated from the client and gets mapped to the following domain object class

public class Bar
{
    public IList<Note> Notes { get; set; }
}

where Note is

public class Note
{
    public string Text { get; set; }

    // other properties excluded for brevity
}

I'd like to map the Note string property on Foo, firstly to the Text property on a new instance of Note and then add that Note to the Notes collection on Bar. I'm using a ValueResolver to perform the first part of this operation (mapping the string to a new instance of Note) but am not sure about how to go about the second part (mapping that item to a item in a collection).

What's the cleanest way of doing this?


回答1:


I'm thinking something like this should work (not tested -- just typing out loud):

Mapper.CreateMap<Foo, Bar>().ForMember(d => d.Notes,
    opt => opt.MapFrom(s => new List<Note> { new Note { Text = s.Note } });

EDIT

You could also use AutoMappers AfterMap functionality. This lambda would be executed after Automapper has done it's regular mappings:

.AfterMap((s,d) => d.Notes.Add(new Note { Text = s.Note }));


来源:https://stackoverflow.com/questions/4733410/map-a-property-to-a-collection-item

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!