Introduction to the object ing tool AutoMapper and the ing tool automapper

Source: Internet
Author: User

Introduction to the object ing tool AutoMapper and the ing tool automapper

AutoMapperIs a class library used to resolve ing and conversion between objects. For our developers, writing code for mutual conversion between objects is a waste of life,AutoMapperIt can help us save a lot of time.

I. What problems does AutoMapper solve?

What problems does AutoMapper solve? Isn't it a problem of object ing conversion?
Yes, of course, but we can ask for more details. Why is there a large number of object ing conversions in the project? (The following applies to non-MVC Projects)

In modern software development, the project hierarchy is further subdivided, and the requirements for objects vary between different levels. This requires data transmission between different levels, data must be converted.

Here are some examples:
In the persistent layer (data access layer), our User object may be an object that contains data of all fields in the User table, or even contains the User's Password information. At the interface layer, we only need to display the user's name and email, without the additional information such as Password. At the same time, it also needs the user's attendance information, this information comes from another table.
In this example, we can find that different layers have different requirements for data objects.
Each layer is responsible for the following:
The persistence layer focuses on data, so it only provides data objects. It does not need to know how the outer layer uses these data objects, nor does it know.
The interface layer focuses only on the data to be displayed.

Then the question is, who will make up for the gap between them?DTO (Data Transfer Object)-- Data Transmission object. WhileAutoMapperIt is a tool for solving the Data Object conversion involved.

Mapper. createMap <Order, OrderDto> (); // create a ing relationship Order-> OrderDtoOrderDto dto = Mapper. map <OrderDto> (order); // use the Map method to directly replace the order object with the OrderDto object.

Smart matching

AutoMapper can automatically identify and match most object attributes:

  • If the attribute names of the source class and target class are the same, directly match
  • The CustomerName of the target type can match the Customer. Name of the source type.
  • The 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> () // matches the WorkEvent in the source class. date TO EventDate. forMember (dest => dest. eventDate, opt => opt. mapFrom (src => src. workEvent. date )). forMember (dest => dest. someValue, opt => opt. ignore () // Ignore attributes 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 match

Test
After defining the rule, you can use the following code to verify that the configuration is correct. The AutoMapperConfigurationException is thrown incorrectly.

Mapper.AssertConfigurationIsValid();
3. AutoMapper handles multiple-to-one Mappings

The question we mentioned at the beginning shows the User's name, email, and attendance information on the interface, which comes from two different tables. This involves the multi-to-one ing problem. The two persistence layer objects need to be mapped to the objects at the display layer of the interface.

Suppose our persistence layer object is like 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 the display layer on my interface 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, we create the EntityMapper class for the purpose of Multi-to-one ing.

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;       }   }

To map multiple source objects to one target object, we use the AutoMapper method to match an existing target object from different source objects one by one. The following code is actually used in MVC:

public ActionResult Index(){          var userId = 23,          var user = _userRepository.Get(userId);          var score = _scoreRepository.GetScore(userId);          var userViewModel = EntityMapper.Map<UserViewModel>(user, score);          return this.View(userViewModel);}
4. Use Profile to configure AutoMapper in the Asp.net MVC Project

ProfileYesAutoMapperTo separate the type ing definitions, so that we can define the AutoMapper type matching code can be more dispersed, reasonable and easy to manage.

ExploitationProfileWe can use our AutoMapper more elegantly in the MVC project. The following is a specific method:

1.Defined in different layersProfile, Only define the type ing in this layer

Inherit from AutoMapping'sProfileClass, overrideProfileNameAttributes andConfigure ()Method.

public class ViewModelMappingProfile: Profile{       public override string ProfileName       {           get           {               return GetType().Name;           }       }       protected override void Configure()       {           Mapper.CreateMap......       }}

2.CreateAutoMapperConfiguration,Provides static methodsConfigure, Loading all layers at a timeProfileDefinition

public class AutoMapperConfiguration{       public static void Configure()       {           Mapper.Initialize(x => x.AddProfile<ViewModelMappingProfile>());           Mapper.AssertConfigurationIsValid();       }}

3.InGlobal. csFile Execution

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

AutoMapperConfiguration.Configuration() 

What is the role of automapper in ORM?

AutoMapper? This is the simplest example.
For example, in ORM, the Model used for interacting with databases has many attribute variable methods. When we interact with other systems (or other structures in the system), for coupling or security or performance considerations (in short, various considerations ), we do not want to pass this Model directly to them. In this case, we will create an anemia Model to store and transmit data. Is Shenma an anemia model? The anemia model (DTO, Data Transfer Object) contains only the attributes of Shenma, and can only save the required Data. Wood has any other redundant method Data or something, A type object used for data transmission. During the creation process, if we do this manually, we will see the Code as follows:
B B = new B ();
B. XXX1 = a. XXX1;
B. XXX2 = a. XXX2;
...
...
...
Return B;

In this case, AutoMapper can automatically map A model to A new B model based on the definitions in model A and model B. This prevents code from being smelly, long, and boring. SO, can be understood as a code generator ......

How to Use the Geometric Sketchpad to draw these two diagrams with an open mind?

Drawing Board tutorial
Chapter 1 Ing tools

Introduction to drawing board first startup and drawing tools

1. Start the Geometric Sketchpad: Click the [start] button in the lower left corner of the desktop, select [all programs] | [GSP4.05], and start the Geometric Sketchpad.

1 shows the open file Geometric Sketchpad.

Figure 1

The canvas window is not a window. Is it very similar to other Windows applications? There is a control menu, the Maximum/minimum, and the title bar of the left-side window is the scroll bar on the right and bottom of the palette toolbar, so that the small canvas can process larger graphics.

The canvas toolbox leaves and moves the cursor over the tool. The tool name will be displayed for a while to see what they are? They select arrow tools, point tools, circular gauge tools, ruler tools, text tools, and custom drawing tools.

Compared with the general drawing software, you will not think that its tools are not enough. The draft is one of the main purposes for drawing geometric shapes. Ry plot, we usually use a ruler and a circular gauge, you can learn from almost all of their Euclidean ry. Because any Euclidean ry can be attributed to the last "point", "line", and "circle ". This idea of self-evident ing has aroused great interest due to the "Three ing problem", which has a significant impact on the long history of mathematics for many mathematical enthusiasts. Drawing from the Euclidean ry is a modern extension of the "ruler ". Because all the basic elements based on the practice and the idea of the mathematical tuwei km are drawn in the same line.

By holding down the edge of the toolbox, you can easily drag the window to any place on the drawing board in different locations and shapes. Try a place and drag it to the shape shown in 2. What is the toolbox?

As its name implies, do you guess what their functions are?

: The selected object. This is its main function. Of course, there are other

: Draw area points on the canvas can be any space or line drawn on the spot. "Line" can be a line segment, Ray, circle, track, function Image

: You cannot draw an elliptical circle, not a little disappointed? (You can draw an ellipse on the geometric drawing board. See chapter 2)

: It is a tool used to draw row rulers. Of course, it is not the only tool ,!

: Plus sign (descriptive text) or OBJECT tag label

: Custom tools. If you think these tools are not enough (for example, you cannot draw a square directly), you can define a new tool.

Select a drawing tool and click it.

You can try to draw a graph, as shown in figure 3.

Figure 3

Click [Tool] and move the mouse to the canvas of the window.

Line chart: Click the ruler of the [Tool], drag the mouse, move the cursor to the "color palette" window, click, drag the mouse to another position, and release the mouse. A segment is displayed.

Circle: Click the [Tool] compass, drag the mouse, move the cursor to the "palette" window, and click (center ), hold down the mouse and drag it to another position (the distance between the start point and the end point is the radius) to release the mouse and return the appearance of a circle.

Painting intersection: Click the arrow tool [select], drag the mouse to move the cursor to the intersection of the line and the circle (the cursor turns to the horizontal display of "Click intersection" from the status bar) Click, intersection occurs. Figure 4:

Figure 4 click a circle

It can only be structured between line segments (including straight lines, rays), circles, and line segments (including straight lines and rays) of the intersection.

Is the drawing tool easier to operate than using a ruler or a circular gauge?

If you take a closer look, you will find that [select arrow tool], [Tool] The ruler has a small triangle in the lower right corner, and the mouse will hold for one second to see what will happen?

[Select] show the arrow tool. As shown in figure 5, there are three tools on it: "move", "Rotate", and "zoom". The key section is used.

Figure 5

Scale tool: expands. There are three tools, as shown in Figure 6: "line", "Ray", "And straight ." We know how to use it to draw a straight line or Ray?

Figure 6

Draw a Ray: move the cursor to the [Tool] ruler, hold down the mouse button, until the [Tool] takes effect, a ruler, do not release the mouse, continue to move the cursor to the ray tool, release the mouse, become a ruler tool. Drawing area of the canvas, click the mouse, and hold down the mouse to drag... the remaining full text>
 

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.