Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map a property to a collection item

Tags:

c#

automapper

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?

like image 510
Russ Cam Avatar asked Jan 19 '11 09:01

Russ Cam


1 Answers

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 }));
like image 108
PatrickSteele Avatar answered Nov 02 '22 21:11

PatrickSteele