Reputation: 141
I'm trying to use Automapper to map from a regular enum to an Enumeration Class (as described by Jimmy Bogard - http://lostechies.com/jimmybogard/2008/08/12/enumeration-classes/). The regular enum doesn't have the same values as the enumeration class does. I would therefore like to map using the 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 help to make this mapping work appreciated! I have attempted just a regular mapping:
Mapper.Map<ProductType, Domain.ProductType>();
.. but the mapped type has a value of 0.
Thanks, Alex
Upvotes: 5
Views: 6257
Reputation: 236268
Here is how Automapper works - it gets public instance properties/fields of destination type, and matches the with public instance properties/fields of source type. Your enum does not have public properties. Enumeration class has two - Value and DisplayName. There is nothing to map for Automapper. Best thing you can use is simple mapper function (I like to use extension methods for that):
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();
}
}
Usage:
ProductType productType = ProductType.ProductType1;
var result = productType.ToDomainProductType();
If you really want to use Automapper in this case, you ca provide this creation method to ConstructUsing
method of mapping expression:
Mapper.CreateMap<ProductType, Domain.ProductType>()
.ConstructUsing(Extensions.ToDomainProductType);
You also can move this creation method to Domain.ProductType
class. Then creating its instance from given enum value will look like:
var result = Domain.ProductType.Create(productType);
UPDATE: You can use reflection to create generic method which maps between enums and 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>();
Upvotes: 5