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

Source: Internet
Author: User

Source: http://www.cnblogs.com/WeiGe/p/3835523.html

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 ~

Second, eat some chestnuts

Chestnut 1 (mapping between two types)

Mapper.createmap<addressdto, address> ();             Addressdto dto = new Addressdto              {                  country = ' China ', city                  = ' Shanghai ',                  Street = ' Jinzhong street '              }; Address address = 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 class productbll{public iproductrepository productrepository{set; get;}            Public productdto createproduct (productdto productdto) {mapper.createmap<productdto, product> ();            Product Product = Mapper.map<productdto, product> (productdto);            Productrepository.addproduct (product);        return productdto; }
Public list<productdto> getproduct () {mapper.createmap<product, productdto> (); list<productdto> arr = new list<productdto> (); Productrepository.getproduct (). ForEach (I-= {arr.) ADD (mapper.map<product, productdto> (i)); }); return arr; } public productdto modifyproduct (productdto productdto) {mapper.createmap<productdto, produ Ct> (); Product Product = Mapper.map<productdto, product> (productdto); Productrepository.modifyproduct (product); return productdto; }}
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 ~

Using system.collections;using system.collections.generic;using system.data;using automapper;namespace infrastructure.utility{//<summary>//AutoMapper Extended Help class///</summary> public static class Autom Apperhelper {//<summary>///Type map//</summary>
public static T-mapto<t> (This object obj) {if (obj = = null) return to default (t); Mapper.createmap (obj. GetType (), typeof (T)); return mapper.map<t> (obj); }///<summary>//Collection List type mapping///</summary>
public static list<tdestination> maptolist<tdestination> (this IEnumerable source) {foreach (var first in source) {var type = first.} GetType (); Mapper.createmap (Type, typeof (Tdestination)); Break } return mapper.map<list<tdestination>> (source); }///<summary>//Collection List type mapping///</summary>
public static list<tdestination> Maptolist<tsource, tdestination> (this ienumerable<tsource> source {//ienumerable<t> type needs to create a mapping of elements mapper.createmap<tsource, tdestination> (); return mapper.map<list<tdestination>> (source); }///<summary>//Type mapping//</summary>
public static Tdestination Mapto<tsource, tdestination> (this tsource source, tdestination destination) WH Ere Tsource:class where Tdestination:class {if (source = = null) return destination; Mapper.createmap<tsource, tdestination> (); Return Mapper.map (source, destination); }///<summary>//DataReader map//</summary>
public static ienumerable<t> datareadermapto<t> (this IDataReader reader) {mapper.reset (); Mapper.createmap<idatareader, ienumerable<t>> (); Return Mapper.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> ();
In the project, we use DTOs to realize the decoupling between the presentation layer and domain model, and use AutoMapper to transform the DTO and domain model, let AutoMapper fly for a while in your project.

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.