This is how Automapper works β it gets the public properties of the instance / field of the destination type and matches the properties / fields of the open instance of the source type. There are no public properties in your listing. The enumeration class has two values ββand DisplayName. For Automapper, there is nothing to match. The best thing you can use is a simple mapper function (I like to use extension methods for this):
public static Domain.ProductType ToDomainProductType( this ProductType productType) { switch (productType) { case ProductType.ProductType1: return Domain.ProductType.ProductType1; case ProductType.ProductType2: return Domain.ProductType.ProductType2; default: throw new ArgumentException(); } }
Using:
ProductType productType = ProductType.ProductType1; var result = productType.ToDomainProductType();
If you really want to use Automapper in this case, you can provide this create method to the ConstructUsing method to display the expression:
Mapper.CreateMap<ProductType, Domain.ProductType>() .ConstructUsing(Extensions.ToDomainProductType);
You can also move this creation method to the Domain.ProductType class. Then creating its instance from the given enum value will look like this:
var result = Domain.ProductType.Create(productType);
UPDATE: you can use reflection to create a generic method that maps between enums and the corresponding 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); }
Using:
var result = productType.ToEnumeration<ProductType, Domain.ProductType>();
Sergey Berezovskiy
source share