Map a property to a collection item

2019-01-23 04:36发布

问题:

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


标签: c# AutoMapper