Before making a DTO conversion, use the AutoMapper. But the level of the DTO is too deep, but the official did not provide a good solution for the nested type, so I realized a bit:
Thinking: Using recursion and reflection is a good way to avoid creating a mapping of nested objects by hand.
First version, submitted to: Https://github.com/AutoMapper/AutoMapper/wiki/Nested-mappings
| The code is as follows |
Copy Code |
<summary> Recursive creation of mappings between types (recursively create mappings between types) Created by Cqwang </summary> <param name= "SourceType" ></param> <param name= "destinationtype" ></param> public static void Createnestedmappers (Type sourcetype, type destinationtype) { propertyinfo[] sourceproperties = sourcetype.getproperties (BindingFlags.Public | BindingFlags.Instance); propertyinfo[] destinationproperties = destinationtype.getproperties (BindingFlags.Public | BindingFlags.Instance); foreach (Var destinationproperty in destinationproperties) { Type destinationpropertytype = Destinationproperty.propertytype; if (Filter (Destinationpropertytype)) Continue PropertyInfo sourceproperty = Sourceproperties.firstordefault (prop => namematches (prop. Name, Destinationproperty.name)); if (sourceproperty = null) Continue Type Sourcepropertytype=sourceproperty.propertytype; if (Destinationpropertytype.isgenerictype) { Type Destinationgenerictype = destinationpropertytype.getgenericarguments () [0]; if (Filter (Destinationgenerictype)) Continue Type Sourcegenerictype = sourcepropertytype.getgenericarguments () [0]; Createmappers (Sourcegenerictype, Destinationgenerictype); } Else { Createmappers (Sourcepropertytype, Destinationpropertytype); } } Mapper.createmap (SourceType, destinationtype); } <summary> Filtration (Filter) </summary> <param name= "Type" ></param> <returns></returns> static bool Filter (type type) { return type. isprimitive | | Noprimitivetypes.contains (type. Name); } static readonly hashset<string> noprimitivetypes = new hashset<string> () {"string", "DateTime", "Decimal"}; private static bool Namematches (string membername, String nametomatch) { return String.Compare (MemberName, Nametomatch, stringcomparison.ordinalignorecase) = = 0; } |
Later found in the self-test, to filter some of the structure may be a lot, more trouble, so I perfected the next, with a second version
The second version has been used and online in some services within the company, which is good. Because it is not related to any business information within the company, just simple ideas and implementation, so here posted to share with you.