c# - Converting string to bool within DataReader with Automapper -
this seems simple question, easy.
i have custom string
bool
map in automapper converts "y"
, "n"
true
, false
. doesn't much simpler:
mapper.createmap<string, bool>().convertusing(str => str.toupper() == "y");
this works fine in primitive example:
public class source { public string isfoo { get; set; } public string bar { get; set; } public string quux { get; set; } } public class dest { public bool isfoo { get; set; } public string bar { get; set; } public int quux { get; set; } } // ... mapper.createmap<string, bool>().convertusing(str => str.toupper() == "y"); mapper.createmap<source, dest>(); mapper.assertconfigurationisvalid(); source s = new source { isfoo = "y", bar = "hello world!", quux = "1" }; source s2 = new source { isfoo = "n", bar = "hello again!", quux = "2" }; dest d = mapper.map<source, dest>(s); dest d2 = mapper.map<source, dest>(s2);
however, let's instead want take source
info datareader
:
mapper.createmap<string, bool>().convertusing(str => str.toupper() == "y"); mapper.createmap<idatareader, dest>(); mapper.assertconfigurationisvalid(); datareader reader = getsourcedata(); list<dest> mapped = mapper.map<idatareader, list<dest>>(reader);
for every dest
in mapped
, isfoo
property true
. missing here?
i ended ditching string
bool
map , instead creating extension methods imemberconfigurationexpression<idatareader>
. extension methods plural because ran this issue numerical info coming db didn't match destination types perfectly, causing inconsistent big numbers. since database stuff out of control, had forcefulness mapper read type. here's ended with:
public static class mapping { public static void init() { mapper.createmap<idatareader, dest>() .formember(s => s.isfoo, opt => opt.readasboolean("isfoo")) .formember(s => s.quux, opt => opt.readasnumber("quux")); mapper.assertconfigurationisvalid(); } public static void readasboolean(this imemberconfigurationexpression<idatareader> opt, string fieldname) { opt.mapfrom(reader => reader.getstring(reader.getordinal(fieldname)).toupper() == "y"); } public static void readasnumber(this imemberconfigurationexpression<idatareader> opt, string fieldname) { opt.mapfrom(reader => reader.getdecimal(reader.getordinal(fieldname))); } }
the duplication of property names strings goes against grain, suspect more automapper skills create more elegant. now, @ to the lowest degree works.
c# .net automapper
No comments:
Post a Comment