Automapper enum to Enumeration Class

£可爱£侵袭症+ 提交于 2019-12-05 13:02:41

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>();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!