AutoMapper User Manual (1), automapper User Manual

Source: Internet
Author: User

AutoMapper User Manual (1), automapper User Manual

Reading directory

1. Introduction

2. Basic use

3. Automatically split the ing (Flattening)

4. Custom Field ing (Projection)

5. Verify Configuration validation)

Introduction

AutoMapper is a lightweight class library. Its main function is to convert an object into another object, instead of manual conversion every time.

Common scenarios:
  • The external service interface converts the entities in the logic layer to the fields required by the service consumer.

  • The UI display layer converts a business object to a field to be displayed by the UI.

  • User input and output convert DTO and domain model.

Platforms supported by AutoMapper:
  • . NET 4 +
  • Silverlight 5
  • Windows Phone 8 +
  • . NET for Windows Store apps (WinRT)
  • Windows Universal Apps
  • Xamarin. iOS
  • Xamarin. Android
Basic usage

Install and use NuGet

PM> install-package automapper

Register the ing relationships between two types:

Mapper.CreateMap<Order, OrderDto>();

Use the Map method to generate a new object of the target type. OrderDto is the target type, and order is the source object.

OrderDto dto = Mapper.Map<OrderDto>(order);

By default, AutoMapper automatically matches with the source rule based on the attribute name and assigns a value.
For example, FirstName = FirstName, FirstName = firstname, and mapper are case insensitive.

Configuration

If you use static global er registration, it should be placed when the application is started.
For example, the Application_Start () method in the Global. asax file of ASP. NET.

Test

AutoMapper provides the following methods to verify whether our configuration is valid. If it is invalid, an exception is thrown:

Mapper.AssertConfigurationIsValid();
Flattening)

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

public class Order{    public Customer Customer { get; set; }    public decimal GetTotal()    {        return 10*10;    }} public class Customer    {        public string Name { get; set; }    }

Then match the Order object to a simple OrderDto, which only contains the required fields:

public class OrderDto{    public string CustomerName { get; set; }    public decimal Total { get; set; }}

When we use AutoMapper to create the Order/OrderDto ing configuration, the AutoMapper er will try to find members with matched names in Order. There are three matching methods.

  • Attributes with the same name are mapped, case-insensitive.
  • Map methods with a Get prefix, as shown in the following example:
    The er splits GetTotal in Order into Get and Total words, and maps the second Total to Order in OrderDto.
  • In this example, the er splits the mermername in OrderDto into Customer and Name. Then, search for the Name attribute in the Customer class attribute in Order.

The internal match is based on Pascal's spelling (PascalCase ).

Custom Field ing (Projection)

Automatic split ing can predict the matching between the source object and the target object, but cannot customize the configuration ing. AutoMapper Automatically splits and matches the target and source attributes according to the rules when constructing the target object.
Therefore, although automatic split ing is convenient and intelligent, it is not so precise and controllable. In many scenarios, we need to split the property and map the B and C attributes, or map the D attributes separately.
AutoMapper provides a method for customizing member ing. For example:

public class CalendarEvent{    public DateTime Date { get; set; }    public string Title { get; set; }}

We want to output more fields on the web page:

public class CalendarEventForm{    public DateTime EventDate { get; set; }    public int EventHour { get; set; }    public int EventMinute { get; set; }    public string Title { get; set; }}

Because the property of the target type does not exist in the source, AutoMapper cannot perform exact matching. We need to customize the member ing rules to our type ing configuration.

// Source object var calendarEvent = new CalendarEvent {Date = new DateTime (2008, 12, 15, 20, 30, 0), Title = "holiday company party "}; // configure AutoMapper. Dest is the target expression. Opt is the source expression Mapper. 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); // execute calending CalendarEventForm form = Mapper. map <CalendarEvent, CalendarEventForm> (calendarEvent); form. eventDate. shouldEqual (new DateTime (2008, 12, 15); form. eventHour. shouldEqual (20); form. eventMinute. shouldEqual (30); form. title. shouldEqual ("company holidays ");

The ForMember method allows us to specify two action delegates to configure the ing relationship for each member. In the above example, we use the MapFrom method in the source expression to map the source value to the target Member. This MapFrom method accepts a lambda expression as a parameter. It evaluates the value during object ing, that is, the inert value. The MapFrom parameter can be a lambda expression of any func.

Configuration validation)

We usually perform object ing manually. Although it is boring, it is helpful for us to test conversion. In the basic test of converting the source type to the target type, we still need to test our own applications. AutoMapper also thinks about this. It reduces not only the tasks of manually performing object ing, but also the time required to manually write test code.

AutoMapper provides the AssertConfigurationIsValid method to test our configuration items. Suppose we have a slight error in the source type and target type:

public class Source 
{
public int SomeValue { get; set; }
}
public class Destination{    public int SomeValuefff { get; set; }}

In Destination, we may accidentally input a few more fff errors. It may also be that our source attribute is renamed.

We will test the configuration items, create the ing configuration, and execute the AssertConfigurationIsValid method.

Mapper.CreateMap<Source, Destination>();Mapper.AssertConfigurationIsValid();

An AutoMapperConfigurationException is thrown during code execution. The message is described as follows:

 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  ==============================================================Source -> Destination (Destination member list)ConsoleApplication1.Source -> ConsoleApplication1.Destination (Destination member list)Unmapped properties:SomeValuefff

During the AssertConfigurationIsValid verification, AutoMapper checks the attributes of each target type to match whether an appropriate and equal type exists in the source one by one.

Overriding configuration errors)

Apart from modifying the name of the source and target types. We have three options to solve the error:

  • Custom value parser
  • Project)
  • Use the Ignore () Option

For the third choice, we have a member of the target type, which has other meanings (non-literal or reserved fields). We do not want to convert it. We can configure it as follows:

 Mapper.CreateMap<Source, Destination>()    .ForMember(dest => dest.SomeValuefff, opt => opt.Ignore());

Official documents: https://github.com/AutoMapper/AutoMapper

 

I have taken a bus home for the Chinese New Year and wish you a happy New Year.

Related Article

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: info-contact@alibabacloud.com 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.