Before doing 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:
Idea: Using recursion and reflection is a good way to avoid manually creating a mapping of nested objects.
The first version, which has been submitted to: Https://github.com/AutoMapper/AutoMapper/wiki/Nested-mappings
1 /// <summary>2 ///recursive creation of mappings between types (recursively create mappings between types)3 ///created by Cqwang4 /// </summary>5 /// <param name= "sourcetype" ></param>6 /// <param name= "destinationtype" ></param>7 Public Static voidcreatenestedmappers (Type sourcetype, type destinationtype)8 {9propertyinfo[] sourceproperties = sourcetype.getproperties (BindingFlags.Public |bindingflags.instance);Tenpropertyinfo[] destinationproperties = destinationtype.getproperties (BindingFlags.Public |bindingflags.instance); One foreach(varDestinationpropertyinchdestinationproperties) A { -Type Destinationpropertytype =Destinationproperty.propertytype; - if(Filter (destinationpropertytype)) the Continue; - -PropertyInfo sourceproperty = sourceproperties.firstordefault (prop =namematches (Prop. Name, Destinationproperty.name)); - if(Sourceproperty = =NULL) + Continue; - +Type sourcepropertytype=Sourceproperty.propertytype; A if(Destinationpropertytype.isgenerictype) at { -Type Destinationgenerictype = destinationpropertytype.getgenericarguments () [0]; - if(Filter (destinationgenerictype)) - Continue; - -Type Sourcegenerictype = sourcepropertytype.getgenericarguments () [0]; in createmappers (Sourcegenerictype, destinationgenerictype); - } to Else + { - createmappers (Sourcepropertytype, destinationpropertytype); the } * } $ Panax Notoginseng Mapper.createmap (sourcetype, destinationtype); - } the + /// <summary> A ///filtering (Filter) the /// </summary> + /// <param name= "type" ></param> - /// <returns></returns> $ Static BOOLFilter (Type type) $ { - returnType. isprimitive | |noprimitivetypes.contains (type. Name); - } the - Static ReadOnlyhashset<string> noprimitivetypes =Newhashset<string> () {"String","DateTime","Decimal" };Wuyi the Private Static BOOLNamematches (stringMemberName,stringNametomatch) - { Wu returnString.Compare (MemberName, Nametomatch, stringcomparison.ordinalignorecase) = =0; -}
View Code
Later found in self-test, to filter some of the structure may be a lot of trouble, so they perfected the next, with the second version
The second version has been used and online in some of the services within the company, which is good. Because it does not involve any business information within the company, it is just a simple idea and implementation, so it is posted here for everyone to share.
All code is original, reproduced please indicate the source.
In fact, there is no road, go to the past, is the road.
AutoMapper creating nested Object Mappings (original)