AutoMapper and interface typed collections -
i'm new automapper. sorry if simple.
this sample domain:
i have basket. contains list of food. food either banana or pickle.
i have dtos mirror each class in domain. goal: basketdto, map , contents basket.
this code fails. after last line have basket, it's filled dtos instead of regular entities :(
class program { static void main(string[] args) { mapper.createmap<basketdto, basket>(); mapper.createmap<pickledto, pickle>(); mapper.createmap<bananadto, banana>(); var dto = new basketdto { food = new list<ifood> { new pickledto { name = "bigpickle" }, new bananadto { name = "smallbanana" }, } }; var basketfromdto = mapper.map<basket>(dto); } } // domain classes , interfaces -------------- interface ifood { string name { get; set; } } class banana : ifood { public string name { get; set; } } class pickle : ifood { public string name { get; set; } } class basket { public ilist<ifood> food { get; set; } } // dtos ------------- class basketdto { public ilist<ifood> food { get; set; } } class pickledto : ifood { public string name { get; set; } } class bananadto : ifood { public string name { get; set; } }
what should map children using food ilist? mappin interfaces , hierarchies complex!
thanks lot.
the problem here automapper
doesn't know how want converted. food
items derive ifood
, mapping performing simplest (and correct). can force appropriate mapping creating typeconverter
- might work:
public class foodconverter : typeconverter<ifood, ifood> { protected override ifood convertcore(ifood source) { if (source pickledto) return mapper.map<pickle>(source); if (source bananadto) return mapper.map<banana>(source); return null; } }
this can configured in mapping this:
mapper.createmap<ifood, ifood>().convertusing<foodconverter>();
personally take little further have have dto food items derive from:
interface ifooddto { string name { get; set; } }
this make intention little clearer automapper
.
finally, dont forget call assertconfigurationisvalid
in mapping.
Comments
Post a Comment