AutoMapper usage and automapper usage

Source: Internet
Author: User

AutoMapper usage and automapper usage

I. Intention

During the development process, when an attribute value on an object is assigned to another object-like attribute, there are many attributes. If you do not use tools, you need to instantiate the attribute B assigned to entity A, and then assign the fields of Entity A to the attributes of entity B one by one. Simply write these assignment statements without technical content, A large amount of code is required. If we do A good job, we generally use reflection to assign the attribute to B. Of course, if we use reflection, we need to smoothly assign the attribute to the B attribute, in this way, the code length can be reduced, so there must be some constraints or restrictions. For example, the attribute names must be the same, and the attribute data types must be the same, so that reflection is not laborious. So how to make reflection more flexible and configurable, And the configuration and reflection process can be separated to achieve a single responsibility, AutoMapper is such an open source class library.

2. Understanding AutoMapper

Official Address: http://automapper.org/

GitHub address: https://github.com/AutoMapper/AutoMapper contains AutoMapper source code and application Simple.

Development Guide: https://github.com/AutoMapper/AutoMapper/wiki/Getting-started

From the use of my development process to some scenarios

3. Best practices

The AutoMapper Development Guide has a detailed introduction. I will not talk about it here. If you are free to study it yourself, I will mainly introduce some good practices of AutoMapper, let's look at the project directly.

 

For each project purpose, the solution folder is clearly marked.

2. Take the order as an example (not a real business, just a simple example). Add the OrderModel in the Models object class library and the OrderViewModel in ViewModels. The Code is as follows:

using System;namespace Models{    public class OrderModel    {        public Guid OrderGuid { get; set; }        public string OrderNo { get; set; }        public string OrderCreator { get; set; }        public DateTime OrderDateTime { get; set; }        public string OrderStatus { get; set; }        public string Description { get; set; }        public string Creator { get; set; }        public DateTime CreateDateTime { get; set; }        public string LastModifier { get; set; }        public DateTime LastModifiedDateTime { get; set; }    }}
using System;namespace ViewModels{    public class OrderViewModel    {        public Guid OrderGuid { get; set; }        public string OrderNo { get; set; }        public string OrderCreator { get; set; }        public DateTime OrderDateTime { get; set; }        public string OrderStatus { get; set; }        public string Description { get; set; }     }}

 

Here, we assume that ViewModel does not need to create or modify related fields during use.

3. AutoMapper Configuration

Download AutoMapper Dll from the NuGet Package Manager, right-click and choose AutoMapperProfiles class library> Manage NuGet package> online> search for "AutoMapper" in the upper right corner to download and install

The ModelToViewModelProfile and ViewModelToModelProfile configuration classes are added, inherit the Profile class of AutoMapper, implement the Configure overload method, and introduce the Models & ViewModels class library, ModelToViewModelProfile, and ViewModelToModelProfile Code as follows:

using AutoMapper;using Models;using ViewModels;namespace AutoMapperProfiles{    public class ModelToViewModelProfile:Profile    {        protected override void Configure()        {            CreateMap<OrderModel, OrderViewModel>();        }    }}
using AutoMapper;using Models;using ViewModels;namespace AutoMapperProfiles{    public class ViewModelToModelProfile : Profile    {        protected override void Configure()        {            CreateMap<OrderViewModel, OrderModel>();        }    }}

4. register the configuration

In the AutoMapperRegister project, add the AutoMapperProfileRegister class. Install AutoMapper at and reference the AutoMapperProfiles class library. The Code is as follows:

using AutoMapper;using AutoMapperProfiles;namespace AutoMapperRegister{    public class AutoMapperProfileRegister    {        public static void Register()        {            Mapper.Configuration.AddProfile(new ModelToViewModelProfile());            Mapper.Configuration.AddProfile(new ViewModelToModelProfile());        }    }}

5. Verify on the console whether the switch is successful

Install AutoMapper according to, introduce AutoMapperRegister, Models, ViewModels Dll, and write the Test Code. The Code is as follows (it's time to witness the miracle)

Using System; using System. collections. generic; using System. linq; using System. text; using System. threading. tasks; using AutoMapper; using AutoMapperRegister; using Models; using ViewModels; namespace ConsoleAutoMapperSample {class Program {static void Main (string [] args) {AutoMapperProfileRegister. register (); var order = new OrderModel {OrderGuid = Guid. newGuid (), OrderNo = "201604020001", OrderCreator = "david", OrderDateTime = DateTime. now, OrderStatus = "checked out", Description = "Please provide your invoice"}; var orderView = Mapper. map <OrderModel, OrderViewModel> (order); orderView. orderStatus = "completed"; var updateOrder = Mapper. map <OrderViewModel, OrderModel> (orderView );}}}

After tracing object property changes, all conversions are successful, which is inconvenient. I will release the source code later.

Final source code:

AutoMapperSample.zip

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.