c# - How can I set default value to exceptions in automapper while mapping from string to int type property? -
i trying map 1 object getting problem while mapping empty string type int or non integer string int
, want if such exceptions occur must assign default value it, let -1.
for example have class a
, class b
class { public string a{get;set;} } class b { public int a{get;set;} }
now if map class a
b
using default rule through exception if string empty or non integer.
please me fix problem.
thanks in advance.
i think you're after.
using system; using system.collections.generic; using system.linq; using system.text; using system.threading.tasks; using automapper; using nunit.framework; namespace stackoverflowanswers { public class lineitem { public int id { get; set; } public string productid { get; set; } public int amount { get; set; } } public class model { public int id { get; set; } public string productid { get; set; } public string amount { get; set; } } public class automappingtests { [testfixturesetup] public void testfixturesetup() { mapper.createmap<model, lineitem>() .formember(x => x.amount, opt => opt.resolveusing<stringtointeger>()); } [test] public void testbadstringtodefaultinteger() { // arrange var model = new model() {id = 1, productid = "awesome-product-133-xp", amount = "evil string, mwuahahahah"}; // act lineitem mapping1 = mapper.map<lineitem>(model); // assert assert.areequal(model.id, mapping1.id); assert.areequal(model.productid, mapping1.productid); assert.areequal(0, mapping1.amount); // arrange model.amount = null; // test null, said in options map null -1 // act lineitem mapping2 = mapper.map<lineitem>(model); // assert assert.areequal(-1, mapping2.amount); } } public class stringtointeger : valueresolver<model, int> { protected override int resolvecore(model source) { if (source.amount == null) { return -1; } int value; if (int.tryparse(source.amount, out value)) { return value; // wahayy!! } return 0; // return 0 if not parse! } } }
Comments
Post a Comment