The AutoMapper Object transformation Facet (Object-object Mapping) Object Mapping tool implements conversions between objects and objects. The main application is the conversion between the dto,model,entity or ViewModel of the project, in fact AutoMapper covers all objects (object).
Here's a demonstration of his basic usage:
Public classCustomer { PublicGuid Id {Get;Set; } Public stringNumber {Get;Set; } Public stringName {Get;Set; } PublicDateTime RegDate {Get;Set; } Public stringNote {Get;Set; } Public stringAddress {Get;Set; } Public stringCategoryID {Get;Set; } } Public classProduct { Public stringId {Get;Set; } Public stringNumber {Get;Set; } Public stringName {Get;Set; } Public decimalPrice {Get;Set; } } Public classOrder { PublicCustomer Customer {Get;Set; } PublicProduct Product {Get;Set; } Public decimalQty {Get;Set; } Public decimalGetamount () {returnproduct.price*Qty; } }
First set up these classes, order, customer, product display orders business, these put to the domain layer. In the foreground presentation layer, you may not need the order class so complex, as long as the Orderdto this simple class is OK.
Public class Orderdto { publicstringgetset;} Public string Get Set ; } Public decimal Get Set ; } }
This requires that the order data be transferred to the Orderdto object. Use AutoMapper to convert the code as follows
Public voidTest () {//set up an instantiated object firstCustomer _customer =NewCustomer () {Id=NewGuid ("e8c1d91f-7076-489b-baa8-8f563ba07402"), number="01.001", Name="Miller Canfield Hospital", RegDate=DateTime.Now, Note="Sadfasdfsdafsdaf", Address="opposite the outpatient building, No. 32nd, CCC Road, SSS, xx province", CategoryID=" on" }; Product _product=NewProduct () {Id ="1", Name ="China Style Bureau Daquan", number ="00892", Price =65.8m}; Order _odr=NewOrder () {Customer = _customer,product = _product,qty =6765m}; //Configure AutoMapperMapper.createmap<order,orderdto>() . Formember (dest= = Dest. CustomerName, opt = opt. Mapfrom (src = src. Customer.name))//Defining mapping Rules. Formember (dest = dest. Address, opt + = opt. Mapfrom (src = src. customer.address))//Defining mapping Rules. Formember (dest = dest. Amount, opt = opt. Mapfrom (src = src. Getamount ()));//Defining mapping Rules//Executive MappingOrderdto form = Mapper.map<order, orderdto>(_ODR); Console.WriteLine ("Customer Name:"+form. CustomerName); Console.WriteLine ("Customer Address:"+form. Address); Console.WriteLine ("Total Amount:"+form. Amount); }
Use AutoMapper to establish a mapping relationship before performing the mapping.
Simple usage of AutoMapper