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–> orderdto Orderdto 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 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 ()) //  Ignore 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 classuser{ Public intId {Get;Set; }  Public stringName {Get;Set; }  Public stringEmail {Get;Set; }  Public stringPASSWORKD {Get;Set; }  PublicDateTime Birthday {Get;Set; }} Public classevaluation{ Public intId {Get;Set; }  Public intScore {Get;Set; }}

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

 Public classuserviewmodel{ Public intId {Get;Set; }  Public stringName {Get;Set; }  Public stringEmail {Get;Set; }  Public intScore {Get;Set; }}

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

 Public Static classentitymapper{ Public StaticT map<t> (params Object[] sources)whereT:class       {           if(!sources. Any ()) {return default(T); }           varInitialsource = sources[0]; varMappingresult = map<t>(Initialsource); //Now map the remaining source objects           if(Sources. Count () >1) {Map (Mappingresult, sources. Skip (1).           ToArray ()); }           returnMappingresult; }       Private Static voidMap (ObjectDestinationparams Object[] sources) {           if(!sources. Any ()) {return; }           vardestinationtype =destination.           GetType (); foreach(varSourceinchsources) {               varSourceType =source.               GetType ();           Mapper.map (source, destination, sourcetype, destinationtype); }       }       Private StaticT map<t> (ObjectSourcewhereT:class       {           vardestinationtype =typeof(T); varSourceType =source.           GetType (); varMappingresult =mapper.map (source, sourcetype, destinationtype); returnMappingresult asT; }   }

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          ,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 all layers at once profile Definition

 Public class automapperconfiguration{       publicstaticvoid  Configure ()       {           = = 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

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.