c# - Ignore Mapping all zero properties, AutoMapper? -
i wanna ignore numeric properties 0 value in automapper configuration.
so, i've written following extension method :
public static imappingexpression<tsource, tdestination> ignorezeronumericproperties<tsource, tdestination>(this imappingexpression<tsource, tdestination> expression) { type sourcetype = typeof(tsource); type destinationtype = typeof(tdestination); list<propertyinfo> numericpropertis = sourcetype.getproperties().tolist(); foreach (propertyinfo propertyinfo in numericpropertis) { string sourcepropertyname = propertyinfo.name; type sourcepropertytype = propertyinfo.propertytype; if (!sourcepropertytype.isnumerictype()) continue; bool isthesamepropertyexistindestinationtype = destinationtype.getproperties().any(q => q.name == sourcepropertyname && q.propertytype == sourcepropertytype); if (!isthesamepropertyexistindestinationtype) continue; parameterexpression parameterexpression = expression.parameter(sourcetype, "c"); memberexpression memberexpression = expression.property(parameterexpression, sourcepropertyname); object value = convert.changetype(0, sourcepropertytype); constantexpression constantexpression = expression.constant(value); expression<func<tsource, bool>> lambdaexpression = expression.lambda<func<tsource, bool>>(expression.greaterthan(memberexpression, constantexpression), parameterexpression); func<tsource, bool> func = lambdaexpression.compile(); expression.formember(sourcepropertyname, opt => opt.condition(func)); } return expression; }
i'm using following :
mapper.createmap<attachmentmodel, attachment>().ignorezeronumericproperties();
isnumerictype method :
public static bool isnumerictype(this type type) { if (type == null) { return false; } switch (type.gettypecode(type)) { case typecode.byte: case typecode.decimal: case typecode.double: case typecode.int16: case typecode.int32: case typecode.int64: case typecode.sbyte: case typecode.single: case typecode.uint16: case typecode.uint32: case typecode.uint64: return true; case typecode.object: if (type.isgenerictype && type.getgenerictypedefinition() == typeof(nullable<>)) { return isnumerictype(nullable.getunderlyingtype(type)); } return false; } return false; }
it compiles without problems,
seems doesn't work , 0 properties map. what's problem ?
i find problem.
i've corrected following line :
// q.propertytype == sourcepropertytype removed bool isthesamepropertyexistindestinationtype = destinationtype.getproperties().any(q => q.name == sourcepropertyname); if (!isthesamepropertyexistindestinationtype) continue;
the destination's property type int?
, source's property type int
. condition didn't created.
Comments
Post a Comment