Object Mapping Tool AutoMapper Introduction

Source: Internet
Author: User

AutoMapper is a class library that is used to resolve mapping transformations between objects. For us developers, it's a waste of life to write code between objects, andautomapper can help us save a lot of time.

A. What problems did the AutoMapper solve?

ask AutoMapper to solve the problem? Is it not an object mapping transformation problem?
Of course, but we can ask a little deeper, why is there a lot of object mapping transformations in the project? (This is also true for non-MVC projects)

In the modern software development, the level of the project is more subdivided, and the requirements of the objects differ between different levels, it is necessary to transform the data when passing data between different levels.

To give some practical examples:
In the persistence layer (the data access layer), our user object may be an object that contains data for all the fields in the user table, and even contains password information for the users. And in the interface layer, we just need to display the user's name, email, do not need to password these additional information, at the same time, it also needs the user's attendance information, and this information from another table.
In this example, we can find that the requirements for the data objects are different between the different layers.
Each layer does what is within its purview:
The persistence layer focuses on the data, so only data objects are provided, and it is not necessary to know how the outer layers use the data objects.
The interface layer focuses on the presentation of the data, which only focuses on the data it wants to display.

So the question is, who will make up the gap between them? DTOs (Data Transfer object)--Data transfer objects. and AutoMapper is the tool to solve the data object transformation involved.

In actual development, if you can also directly use the persistence Layer object directly in the business layer or the interface layer, because you think this relationship is not big, the whole project is your own control, although dirty, but quick. As a somewhat neat programmer, I recommend using DTOs to pass data between different tiers. Because when you do a higher level of development, such as developing WEB Service,wcf,web APIs that provide interfaces to the outside of the system, you can understand that these good habits and ideas will help you design these external interfaces better.

Two. How is automapper used?

Let's start with a simple example, which is to define the mapping between the order object and the Orderdto object. (We call the order as the source class, Orderdto is called the target class)

Mapper.createmap<order, orderdto> ();//Create a mapping relationship order–> orderdtoorderdto dto = mapper.map<orderdto> ( order);//Use the map method to replace the order object directly with the Orderdto object

Smart Match

AutoMapper can automatically identify and match most object properties:

    • If the property names of the source and target classes are the same, the direct match
    • The customername of the target type can match the customer.name of the source type
    • Total of the target type can match the Gettotal () method of the source type

Custom matching Rules

AutoMapper also supports custom matching rules

Mapper.createmap<calendarevent, calendareventform> ()                        //property match, Matches workevent.date to eventdate in the source class                        . Formember (dest = dest. Eventdate, opt = opt. Mapfrom (src = src. workevent.date))                        . Formember (dest = dest. Somevalue, opt = opt. Ignore ())//ignores the properties in the target class                        . Formember (dest = dest. TotalAmount, opt = opt. Mapfrom (src = src. TotalAmount?? 0)//complex match                        . Formember (dest = dest. OrderDate, opt = opt. Uservalue<datetime> (DateTime.Now)) fixed value matching

Test
When you have finished defining the rules, you can use the following code to verify that the configuration is correct. The exception automapperconfigurationexception is thrown incorrectly.

Mapper.assertconfigurationisvalid ();
Three. AutoMapper handles many-to-one mappings

Among the questions we mentioned, the interface shows user's name, email, and attendance information from 2 different tables. This involves a multiple-to-one mapping problem, where 2 persistent layer objects need to be mapped to an interface display layer object.

Let's say that our persistence layer object is this:

public class user{Public       int Id {get; set;}       public string Name {get; set;}       public string Email {get; set;}       public string Passworkd {get; set;}       Public DateTime Birthday {get; set;}} public class evaluation{Public       int Id {get; set;}       public int score {get; set;}}

in ASP. NET MVC, the ViewModel of my interface display layer is like this

public class userviewmodel{Public       int Id {get; set;}       public string Name {get; set;}       public string Email {get; set;}       public int score {get; set;}}

Next, in order to achieve the goal of many-to-one mappings, we create this entitymapper class

public static class entitymapper{public static T map<t> (params object[] sources) where T:class { if (!sources.           Any ()) {return default (T);           } var initialsource = sources[0];           var mappingresult = map<t> (Initialsource); Now map the remaining source objects if (sources. Count () > 1) {Map (Mappingresult, sources. Skip (1).           ToArray ());       } return Mappingresult; } private static void Map (object destination, params object[] sources) {if (!sources.           Any ()) {return; } var destinationtype = destination.           GetType (); foreach (var source in sources) {var sourcetype = source.               GetType ();           Mapper.map (source, destination, sourcetype, destinationtype);  }} private static T Map<t> (object source) where T:class     {var destinationtype = typeof (T); var sourcetype = source.           GetType ();           var Mappingresult = Mapper.map (source, sourcetype, destinationtype);       return Mappingresult as T; }   }

In order to implement multiple source object mappings for a target object, we used the AutoMapper method to match an existing target object one after another from different source objects. Here is the code actually used in MVC:

Public ActionResult Index () {          var userId = all,          var user = _userrepository.get (userId);          var score = _scorerepository.getscore (userId);          var Userviewmodel = entitymapper.map<userviewmodel> (user, score);          return this. View (Userviewmodel);}
Four. Configure automapper in an ASP. NET MVC project using profile

profile is used to separate the definition of type mappings in automapper , so that our definition of AutoMapper type matching code can be more decentralized, reasonable and manageable.

With profile, we can use our automapper more gracefully in MVC projects. Here are the specific methods:

1. define profiles in different tiers , defining only type mappings in this layer

Inherit the profile class of automapping, overriding the ProfileName property and the Configure () method.

public class viewmodelmappingprofile:profile{public       override string ProfileName       {           get           {               Return GetType (). Name;           }       }       protected override void Configure ()       {           mapper.createmap ...       }}

2. Create automapperconfiguration, provide static method Configure, Load the profile definition in all layers at once

public class automapperconfiguration{public       static void Configure ()       {           mapper.initialize (x = x). Addprofile<viewmodelmappingprofile> ());           Mapper.assertconfigurationisvalid ();       }}

3. Execute in the Global.cs file

Finally, before the program starts in the Global.cs file, the method is called

Category: [39]open Source

Object Mapping Tool AutoMapper Introduction

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.