Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automapper: Mapping a property value of an object to a string

Tags:

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);
like image 555
Paul Hadfield Avatar asked Dec 14 '10 13:12

Paul Hadfield


People also ask

How do I use AutoMapper to list a map?

Once you have your types, and a reference to AutoMapper, you can create a map for the two types. Mapper. CreateMap<Order, OrderDto>(); The type on the left is the source type, and the type on the right is the destination type.

Does AutoMapper map private properties?

By default, AutoMapper only recognizes public members. It can map to private setters, but will skip internal/private methods and properties if the entire property is private/internal.

Can AutoMapper map enums?

The built-in enum mapper is not configurable, it can only be replaced. Alternatively, AutoMapper supports convention based mapping of enum values in a separate package AutoMapper.

How does AutoMapper work in C#?

AutoMapper in C# is a library used to map data from one object to another. It acts as a mapper between two objects and transforms one object type into another. It converts the input object of one type to the output object of another type until the latter type follows or maintains the conventions of AutoMapper.


1 Answers

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);
like image 53
PatrickSteele Avatar answered Sep 18 '22 16:09

PatrickSteele