Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapping all properties of 'X' type with AutoMapper

I've just started using AutoMapper and so far found it very straight-forward and time-saving.

Just one thing I'm not sure about - how do I map all the properties of a given type in the same way?

Can this be done with AutoMapper in a single statement, using a lambda, as with regular mapping?

like image 859
Jonathan Avatar asked Mar 07 '10 02:03

Jonathan


People also ask

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.

Is AutoMapper faster than manual mapping?

Inside this article, it discusses performance and it indicates that Automapper is 7 times slower than manual mapping. This test was done on 100,000 records and I must say I was shocked.

When should I use AutoMapper?

AutoMapper is used whenever there are many data properties for objects, and we need to map them between the object of source class to the object of destination class, Along with the knowledge of data structure and algorithms, a developer is required to have excellent development skills as well.

Can AutoMapper map collections?

Collection. Adds ability to map collections to existing collections without re-creating the collection object.


1 Answers

What you are looking for is known as a CustomTypeConverter. These are global in scope, and only need to be configured once.

The syntax is:

Mapper.CreateMap<TSourceProperty,TDestinationProperty>().ConvertUsing(argument);

where argument can be

  1. An implementation of ITypeConverter<TSourceProperty,TDestinationProperty>
  2. A Func<TSourceProperty,TDestinationProperty>

Jimmy Bogard has an article on implementing CustomTypeConverters at http://www.lostechies.com/blogs/jimmy_bogard/archive/2009/05/05/automapper-feature-custom-type-converters.aspx .

More information is also provided in the CustomTypeConverter page of the AutoMapper documentation.

Oh, and by the way (since I want Omu's bounty) you can also do this by switching to valueinjecter.

like image 130
smartcaveman Avatar answered Oct 15 '22 06:10

smartcaveman