【问题标题】:Automapper enum to Enumeration ClassAutomapper 枚举到枚举类
【发布时间】:2014-06-27 13:46:01
【问题描述】:

我正在尝试使用 Automapper 从常规枚举映射到枚举类(如 Jimmy Bogard 所述 - http://lostechies.com/jimmybogard/2008/08/12/enumeration-classes/)。常规枚举与枚举类没有相同的值。因此,如果可能,我想使用名称进行映射:

枚举:

public enum ProductType
{
    ProductType1,
    ProductType2
}

枚举类:

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()
    {
    }
}

感谢您对制作此映射工作的任何帮助!我只尝试了常规映射:

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

.. 但映射类型的值为 0。

谢谢, 亚历克斯

【问题讨论】:

  • 无论你是谁,对反对票的一些反馈都会很棒,谢谢

标签: c# enums automapper


【解决方案1】:

这是 Automapper 的工作方式 - 它获取目标类型的公共 instance 属性/字段,并与源类型的公共 instance 属性/字段匹配。您的枚举没有公共属性。枚举类有两个——Value 和 DisplayName。 Automapper 没有可映射的内容。您可以使用的最好的东西是简单的映射器功能(我喜欢为此使用扩展方法):

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();
    }
}

用法:

ProductType productType = ProductType.ProductType1;
var result = productType.ToDomainProductType();

如果你真的想在这种情况下使用Automapper,你可以将这个创建方法提供给ConstructUsing映射表达式的方法:

Mapper.CreateMap<ProductType, Domain.ProductType>()
      .ConstructUsing(Extensions.ToDomainProductType);

您也可以将此创建方法移至Domain.ProductType 类。然后从给定的枚举值创建它的实例将如下所示:

var result = Domain.ProductType.Create(productType);

更新:您可以使用反射来创建在枚举和适当的枚举类之间映射的通用方法:

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);
}

用法:

var result = productType.ToEnumeration<ProductType, Domain.ProductType>();

【讨论】:

  • 感谢您的精彩解释,我现在明白问题所在了。我想我最终可能会将枚举更改为具有匹配的值,并映射到枚举类的 Value 实例成员。我比什么都好奇!我认为反射版本相当不错,所以在某些时候可能会派上用场。谢谢
  • 这就是我最终要做的——如果你确实想从一个与枚举类具有相同值的枚举进行映射(我知道一个不同的问题)mapper.CreateMap( ) .ConstructUsing(dto => Enumeration.FromValue((int)dto.SourceValue));
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-16
  • 1970-01-01
  • 1970-01-01
  • 2011-04-03
  • 2013-02-03
相关资源
最近更新 更多