26

Using Automapper, how do you handle the mapping of a property value on an object to an instance of a string. Basically I have a list of Role objects and I want to use Automapper to map the content of each "name" property to a corresponding list of string (so I just end up with a list of strings). I'm sure it has an obvious answer, but I can't find the mapping that I need to add to "CreateMap" to get it to work.

An example of the relevant code is shown below:

public class Role
{
   public Guid Id{get;set;}
   public string Name{get;set;}
   ...
   ...
}

// What goes in here?
Mapper.CreateMap<Role, string>().ForMember(....);

var allRoles = Mapper.Map<IList<Role>, IList<string>>(roles);

1 Answer 1

59

I love Automapper (and use it in a number of projects), but wouldn't this be easier with a simple LINQ statement?

var allRoles = from r in roles select r.Name

The AutoMapper way of accomplishing this:

Mapper.CreateMap<Role, String>().ConvertUsing(r => r.Name);
Sign up to request clarification or add additional context in comments.

6 Comments

In this instance you are probably right and it would fit in with our infrastructure, but even so I'd be interested in knowing if/how it could be done with Automapper.
Sorry -- should have answered your original question. :) This should work: Mapper.CreateMap<Role, String>().ConvertUsing(r => r.Name);
Thanks for providing an Automapper way of doing this, it works exactly as I'd hoped.
How do you do the reverse, setting the role from the string?
@Chris -- Automapper way to do the reverse: Mapper.CreateMap<string, Role>().ForMember(dest => dest.Name, opt => opt.MapFrom(src => src)) should work I think.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.