AutoMapper User Manual (i)

Source: Internet
Author: User

Read Catalogue

1. Introduction

2. Basic use

3. Auto-split mapping (flattening)

4. Custom field mapping (Projection)

5. Verifying configuration (config validation)


AutoMapper is a lightweight class library, and the main function is to convert an object to another object, rather than manually converting it every time.

Several common usage scenarios:
    • An external service interface that transforms the entity of the logic layer into the field required by the service consumer.

    • The UI presentation layer transforms the business object into a field that the UI needs to expose.

    • The user's input and output, the DTO and the domain model of the cross-turn.

AutoMapper Supported Platforms:
    • . NET 4+
    • Silverlight 5
    • Windows Phone 8+
    • . NET for Windows Store apps (WinRT)
    • Windows Universal Apps
    • Xamarin.ios
Basic use

NuGet installation Uses

Pm> Install-package AutoMapper

To register a mapping relationship between 2 types:

Mapper.createmap<order, orderdto> ();

The map method is used to generate the target type new object, Orderdto is the target type, and order is the source object.

Orderdto DTO =<orderdto> (order);

The default is to automatically match the source with the AutoMapper according to the property name, assigning the value.
Example: Firstname=firstname,firstname=firstname,mapper is case insensitive.


If you register with a static global mapper, you should put it on when the application starts.
For example, the Application_Start () method in an ASP. Global.asax file.


AutoMapper provides the following method to verify that our configuration is valid and invalid throws an exception:

Mapper.assertconfigurationisvalid ();
Auto-split mapping (flattening)

In practice, we often need to map a complex object to a simple object for use in the UI, for example:

 Public classorder{ PublicCustomer Customer {Get;Set; }  Public decimalgettotal () {return Ten*Ten; }}  Public classCustomer { Public stringName {Get;Set; } }

Then match the order object to a simple orderdto that contains only the fields we need:

 Public class orderdto{    publicstringgetset;}      Public decimal Get Set ; }}

When we created the Order/orderdto mapping configuration using AutoMapper, the AutoMapper Mapper tried to find the names matching members in order, with 3 matching methods.

    • Properties with the same name are mapped and are not case-sensitive.
    • A method with a get prefix is mapped, as in the example:
      The mapper splits the gettotal in order into get, total 2 words, and the second total matches the order in Orderdto.
    • The target type attribute is split, as in the example: the mapper divides the CustomerName in Orderdto into customer, Name. Then in order, go to the Customer class property to find the property of name.

The internal match is based on the Pascal orthography (pascalcase).

custom field mapping (Projection)

Auto-split mapping can pre-contract the matching of source objects to target objects, but cannot customize configuration mappings. AutoMapper when constructing the target object, it automatically matches the target with the source attribute by the rule.
Therefore, automatic partition mapping is convenient and intelligent, but it is not so precise and controllable. In many scenarios, what we need more is to split the A attribute on map B, C 2 properties, or map the D attribute separately.
AutoMapper provides a way to customize member mappings. For example:

 Public class calendarevent{    publicgetset;}      Public string Get Set ; }}

We want to output more fields on the Web page:

 Public classcalendareventform{ PublicDateTime Eventdate {Get;Set; }  Public intEventhour {Get;Set; }  Public intEventminute {Get;Set; }  Public stringTitle {Get;Set; }}

Because the property of the target type does not exist on the source, AutoMapper cannot complete the exact match. We need to customize the member mapping rules to our type mapping configuration above.

//Source ObjectvarCalendarevent =Newcalendarevent {Date=NewDateTime ( -, A, the, -, -,0), Title="Holiday Company Party"    };//Configure AutoMapper. Dest is the target expression. Opt is the source expressionMapper.createmap<calendarevent, calendareventform>()    . Formember (dest= = Dest. Eventdate, opt = opt. Mapfrom (src =src. Date.Date)). Formember (dest= = Dest. Eventhour, opt = opt. Mapfrom (src =src. Date.hour)). Formember (dest= = Dest. Eventminute, opt = opt. Mapfrom (src =src. Date.minute));//Performing MappingsCalendareventform form =<calendarevent, calendareventform>(calendarevent); a form. Eventdate.shouldequal (NewDateTime ( -, A, the) ); form. Eventhour.shouldequal ( -); form. Eventminute.shouldequal ( -); form. Title.shouldequal ("Holiday Company Party");

The Formember method allows us to specify 2 action delegates to configure the mapping relationship for each member. In the example above, we used the Mapfrom method in the source expression to perform the mapping of the source value to the target member. This mapfrom method takes a lambda expression as a parameter, which is evaluated during object mapping, that is, lazy evaluation. The Mapfrom parameter can be a lambda expression of any of the func.

Verifying configurations (Configuration validation)

We usually do the object mapping manually, although it is very dull, but it is helpful for us to test the conversion. We still need to test our own applications for this source-to-target-type conversion fundamentals test. AutoMapper also thought of this, which reduces not only the things we do with object mapping manually, but also saves us time in writing test code manually.

AutoMapper provides the Assertconfigurationisvalid method to test our configuration items. Let's say we have a slight error on the source type and the target type:

 Public class
Public int Get Set
 Public class destination{    publicintgetset;}}

On the destination, we may accidentally input errors, a few more fff. It is also possible that our source property has been renamed.

We go to test the configuration item, create the mapping configuration, and execute the Assertconfigurationisvalid method.

Mapper.createmap<source, destination>(); Mapper.assertconfigurationisvalid ();

A Automapperconfigurationexception exception is thrown during code execution, describing the message as:

Unmapped members were found. Review the types and members below. Add a custom mapping expression, ignore, add a custom resolver, or modify the source/destination type  = = ============================================================,  Consoleapplication1.destination (Destination member list) Unmapped properties:somevaluefff

Assertconfigurationisvalid during validation, AutoMapper examines the properties of each target type, one by one, to match whether there is a suitable equality type in the source.

Exception handling (overriding configuration errors)

Except we go to modify the source and destination type names. We have 3 options to resolve the error:

    • Custom Value Resolver
    • Specify field mappings (Projection)
    • Use the Ignore (Ignore ()) option

Regarding the third option, we have a member in the target type, it has other meanings (not literal or reserved fields), we do not want to convert, we can configure as follows:

Mapper.createmap<source, destination>()    = dest. SOMEVALUEFFF, opt = opt. Ignore ());

Official Document: Https://

A ride home for the New year, I wish you all a happy.

AutoMapper User Manual (i)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.