Let AutoMapper fly for a while in your project (turn)

Source: Internet
Author: User

Let's talk about DTOs.

What is a DTO?

DTOs (Data Transfer object) are data transfer objects, which is simply an object, except that it is all in it.

Why do you use DTOs?

1, DTOs pay more attention to data, the domain objects are properly encapsulated, so that the behavior of the domain objects will not be exposed to the performance layer

2. DTOs are designed for the needs of the UI, and the domain model is designed for business. So dtos are more suitable for interacting with the presentation layer, and we have implemented the decoupling between the presentation layer and the domain model through the DTO, so changing the domain model does not affect the UI layer

3, DTOs Plainly is the data, does not contain any business logic, is a thin type of object, use can be used in accordance with the different UI needs of flexible application

AutoMapper

Now that we know the benefits of using a DTO, we certainly want to use it right away, but here's a question: how do we achieve a transformation between a DTO and a domain model?

There are two ideas, we either write the conversion code ourselves, or use a tool. However, as far as the application is concerned, I still feel that using the tool is relatively simple and quick. In fact, there are a lot of such conversion tools, but I decided to use AutoMapper, because it is lightweight, but also very popular, the foreign Daniel use it. With AutoMapper, the conversion between DTOs and domain model can be implemented conveniently, and it is a powerful object-object mapping tool.

First, how to add AutoMapper to the project?

By using the Open Tool-Library Package Manager-Package management control platform in VS, enter "install-package automapper" command, you can add AutoMapper to the project ~

Two, eat chestnut chestnuts 1 (mapping between two types)
Mapper.createmap<addressdto, address>();              New Addressdto              {                  "China",                  "Shanghai",                   " Jinzhong Street "                = mapper.map<addressdto,address> (Dto);

Chestnut 2 (two mapped objects have some field names that are not the same)

Addressdto to address map, addressdto field countryname to correspond to address field country:

Mapper.createmap<addressdto, Address> (). Formember (d = d.country, opt = = opt. Mapfrom (s = s.countryname));

Chestnut 3 (Mapping between list types)

Source type List<address>, target type list<addressdto>:

automapper.mapper.createmap< Address, Addressdto >(); var addressdtolist = automapper.mapper.map<list< Address, list< addressdto >> (addresslist );

Chestnut 4 (mapping in the application of Incremental modification)
 Public classproductbll{public iproductrepository productrepository{Set;Get; }  Publicproductdto createproduct (productdto productdto) {Mapper.createmap<productdto, product>(); Product Product= Mapper.map<productdto, product>(productdto);            Productrepository.addproduct (product); returnproductdto; } PublicList<productdto>getproduct () {Mapper.createmap<product, productdto>(); List<ProductDTO> arr =NewList<productdto>(); Productrepository.getproduct (). ForEach (i={arr. ADD (Mapper.map<product, productdto>(i));            }); returnarr; }          Publicproductdto modifyproduct (productdto productdto) {Mapper.createmap<productdto, product>(); Product Product= Mapper.map<productdto, product>(productdto);            Productrepository.modifyproduct (product); returnproductdto; }}

Third, make automapper use become simple

How do you feel about eating the chestnuts above? If you want to continue eating, check out the AutoMapper API documentation! If you really want to use it in the project, I think the AutoMapper method should be done some sorting, it is best to encapsulate, here I extend the way to encapsulate it as a automapperhelper, so that later use automapper change so Easy ~

usingSystem.Collections;usingSystem.Collections.Generic;usingSystem.Data;usingAutoMapper;namespaceinfrastructure.utility{/// <summary>    ///automapper Extension Helper class/// </summary>     Public Static classAutomapperhelper {/// <summary>        ///Type mapping/// </summary> Public StaticT mapto<t> ( This Objectobj) {            if(obj = =NULL)return default(T); Mapper.createmap (obj. GetType (),typeof(T)); returnMapper.map<t>(obj); }        /// <summary>        ///Collection List Type mappings/// </summary> Public StaticList<tdestination> maptolist<tdestination> ( ThisIEnumerable Source) {            foreach(varFirstinchsource) {                varType =First .                GetType (); Mapper.createmap (Type,typeof(tdestination));  Break; }            returnMapper.map<list<tdestination>>(source); }        /// <summary>        ///Collection List Type mappings/// </summary> Public StaticList<tdestination> Maptolist<tsource, Tdestination> ( ThisIenumerable<tsource>source) {            //ienumerable<t> types need to create a mapping of elementsMapper.createmap<tsource, tdestination>(); returnMapper.map<list<tdestination>>(source); }        /// <summary>        ///Type mapping/// </summary> Public StaticTdestination Mapto<tsource, Tdestination> ( ThisTSource Source, tdestination destination)whereTSource:class            whereTdestination:class        {           if(Source = =NULL)returndestination; Mapper.createmap<tsource, tdestination>(); returnMapper.map (source, destination); }        /// <summary>        ///DataReader Mapping/// </summary> Public StaticIenumerable<t> datareadermapto<t> ( ThisIDataReader Reader)            {Mapper.reset (); Mapper.createmap<idatareader, ienumerable<t>>(); returnMapper.map<idatareader, ienumerable<t>>(reader); }    }}

You can use the following chestnuts like this:

// Object Mappings Shipinfomodel  Shipinfomodel =  shipinfo.mapto<shipinfomodel>(); // List Mappings list< Shipinfomodel > shipinfomodellist = shipinfolist.maptolist<shipinfomodel> ();

Summary

Use DTOs in the project to achieve the decoupling of the presentation layer and domain model, using AutoMapper to transform the DTO and domain model, let AutoMapper fly for a while in your project

Source: http://blog.csdn.net/CsethCRM/article/details/52934325

Let AutoMapper fly for a while in your project (turn)

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.