Automapper enumeration for enumeration class

I am trying to use Automapper to match from a regular enumeration to an enumeration class (as described by Jimmy Bogard - http://lostechies.com/jimmybogard/2008/08/12/enumeration-classes/ ). A regular enumeration does not have the same meanings as an enumeration class. Therefore, I would like, if possible, to use a map named Name:

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 tried just regular mapping:

 Mapper.Map<ProductType, Domain.ProductType>(); 

.. but the type being mapped is 0.

Thanks Alex

+4
enums c # automapper
source share
1 answer

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>(); 
+3
source share

All Articles