Nullable datetime to datetime converter automapper -
i have situation dtos require datetime properties pocos use nullable datetimes. avoid having create formember mappings every property condition created itypeconverter<datetime?, datetime>. problem ran when both dto , poco have nullable datetimes converter called. destinationtype datetime though property nullable datetime. idea how make converter run actual nullable datetimes?
public class foodto { public datetime? foodate { get; set; } } public class foopoco { public datetime? foodate { get; set; } } class program { static void main(string[] args) { mapper.createmap<foodto, foopoco>(); mapper.createmap<datetime?, datetime>() .convertusing<nullabledatetimeconverter>(); var poco = new foopoco(); mapper.map(new foodto() { foodate = null }, poco); if (poco.foodate.hasvalue) console.writeline( "this should null : {0}", poco.foodate.value.tostring()); //value set else console.writeline("mapping worked"); } } public class nullabledatetimeconverter : itypeconverter<datetime?, datetime> { // since both nullable date times , handles converting // nullable datetime not expect called. public datetime convert(resolutioncontext context) { var sourcedate = context.sourcevalue datetime?; if (sourcedate.hasvalue) return sourcedate.value; else return default(datetime); } } i found post automapper typeconverter mapping nullable type not-nullable type little help.
without looking suspect calling typecoverter because best match types being converted.
if create typeconverter correct types should work fine. eg:
public class datetimeconverter : itypeconverter<datetime?, datetime> { public datetime convert(resolutioncontext context) { var sourcedate = context.sourcevalue datetime?; if (sourcedate.hasvalue) return sourcedate.value; else return default(datetime); } } public class nullabledatetimeconverter : itypeconverter<datetime?, datetime?> { public datetime? convert(resolutioncontext context) { var sourcedate = context.sourcevalue datetime?; if (sourcedate.hasvalue) return sourcedate.value; else return default(datetime?); } } note if wish these can further simplified to
public class datetimeconverter : typeconverter<datetime?, datetime> { protected override datetime convertcore(datetime? source) { if (source.hasvalue) return source.value; else return default(datetime); } } public class nullabledatetimeconverter : typeconverter<datetime?, datetime?> { protected override datetime? convertcore(datetime? source) { return source; } } then initialise both converters:
mapper.createmap<datetime?, datetime>().convertusing<datetimeconverter>(); mapper.createmap<datetime?, datetime?>().convertusing<nullabledatetimeconverter>(); mapper.assertconfigurationisvalid();
Comments
Post a Comment