c# - automapper: skipping/ignoring nested types -
i'm trying create map between domain object , viewmodel support use case feels quite common. fact can't find solution makes me think i'm approaching problem incorrectly. here's psuedo code represents source , destination types:
public class domainclass { public nesteddomainclass1 nesteddomainclass1{ get; set; } } public class nesteddomainclass1 { public nesteddomainclass2 nesteddomainclass2 { get; set; } } public class nesteddomainclass2 { public string propertya { get; set; } public string propertyb { get; set; } public string propertyc { get; set; } } public class domainviewmodel { public string propertya { get; set; } public string propertyb { get; set; } public string propertyc { get; set; } }
as can see, domainviewmodel
maps domainclass.nesteddomainclass1.nesteddomainclass2
. however, reasons aren't entirely relevant, can't create mapping @ level. instead have map 2 levels higher:
mapper.createmap<domainobj, domainviewmodel>();
this unfortunate, minute this, can no longer rely on automapper conventions automagically map named properties, , end having write lot of highly repetitive code:
mapper.createmap<domainclass, domainviewmodel>().formember(dest=>dest.propertya, opt=>opt.mapfrom(source=>source.nesteddomainclass1.nesteddomainclass2.propertya)); mapper.createmap<domainclass, domainviewmodel>().formember(dest=>dest.propertyb, opt=>opt.mapfrom(source=>source.nesteddomainclass1.nesteddomainclass2.propertyb));
i've played recognizedestinationprefixes
, recognizedestinationpostfixes
methods in hopes of getting automapper "skip" directly property i'd map (nesteddomainclass2
), no luck. appreciated!
that's because you're trying map between 2 different types. need this:
mapper.createmap<nesteddomainclass2, domainviewmodel>(); mapper.assertconfigurationisvalid(); var dvm = mapper.map<nesteddomainclass2, domainviewmodel> (obj.nesteddomainclass1.nesteddomainclass2);
however if want to, can hide detail defining typeconverter
. should work:
public class domaintypeconverter : typeconverter<domainclass, domainviewmodel> { protected override domainviewmodel convertcore(domainclass source) { return mapper.map<nesteddomainclass2, domainviewmodel> (source.nesteddomainclass1.nesteddomainclass2); } }
you can define mapping this:
mapper.createmap<nesteddomainclass2, domainviewmodel>(); mapper.createmap<domainclass, domainviewmodel>() .convertusing(new domaintypeconverter()); mapper.assertconfigurationisvalid();
and use this:
var dvm = mapper.map<domainclass, domainviewmodel>(dc);
Comments
Post a Comment