c# - Automapper enum to Enumeration Class -
i'm trying use automapper map regular enum enumeration class (as described jimmy bogard - http://lostechies.com/jimmybogard/2008/08/12/enumeration-classes/). regular enum doesn't have same values enumeration class does. therefore map using name if possible:
enum:
public enum producttype { producttype1, producttype2 }
enumeration class:
public class producttype : enumeration { public static producttype producttype1 = new producttype(8, "product type 1"); public static producttype producttype2 = new producttype(72, "product type 2"); public producttype(int value, string displayname) : base(value, displayname) { } public producttype() { } }
any make mapping work appreciated! have attempted regular mapping:
mapper.map<producttype, domain.producttype>();
.. mapped type has value of 0.
thanks, alex
here how automapper works - gets public instance properties/fields of destination type, , matches public instance properties/fields of source type. enum not have public properties. enumeration class has 2 - value , displayname. there nothing map automapper. best thing can use simple mapper function (i use extension methods that):
public static domain.producttype todomainproducttype( producttype producttype) { switch (producttype) { case producttype.producttype1: return domain.producttype.producttype1; case producttype.producttype2: return domain.producttype.producttype2; default: throw new argumentexception(); } }
usage:
producttype producttype = producttype.producttype1; var result = producttype.todomainproducttype();
if want use automapper in case, ca provide creation method constructusing
method of mapping expression:
mapper.createmap<producttype, domain.producttype>() .constructusing(extensions.todomainproducttype);
you can move creation method domain.producttype
class. creating instance given enum value like:
var result = domain.producttype.create(producttype);
update: can use reflection create generic method maps between enums , appropriate enumeration class:
public static tenumeration toenumeration<tenum, tenumeration>(this tenum value) { string name = enum.getname(typeof(tenum), value); var field = typeof(tenumeration).getfield(name); return (tenumeration)field.getvalue(null); }
usage:
var result = producttype.toenumeration<producttype, domain.producttype>();
Comments
Post a Comment