首页 > 解决方案 > 为什么我的枚举到类转换的自定义成员解析器不起作用?

问题描述

我收到异常消息:

没有为类型“NotificationArea”和“System.Object”定义二元运算符 NotEqual

源枚举:

public enum NotificationArea
{
    One,
    Two,
    Three
}

目的地等级:

public class EnumValue
{
    public EnumValue()
    {
    }

    public EnumValue(Enum tEnum)
    {
        Id = Convert.ToInt32(tEnum);
        Name = GetEnumValue(tEnum, tEnum.GetType());
    }

    public int Id { get; set; }
    public string Name { get; set; }

    public string GetEnumValue(Enum tEnum, Type type)
    {
        MemberInfo member = type.GetMember(tEnum.ToString())[0];

        if (member.GetCustomAttribute<DisplayAttribute>() != null)
        {
            DisplayAttribute attribute = member.GetCustomAttribute<DisplayAttribute>();
            return attribute.Name;
        }

        return tEnum.ToString();
    }
}

转换类:

public class EnumConverter : IMemberValueResolver<Notification,
     NotificationModel, NotificationArea, EnumValue>
{
    public EnumValue Resolve(Notification source, NotificationModel destination, 
        NotificationArea sourceMember, EnumValue destMember, ResolutionContext context)
    {
        var model = source.Area.ToDisplay();
        return model;
    }
}

显示扩展:

public static EnumValue ToDisplay(this Enum value)
{
    var display = new EnumValue(value);
    return display;
}

执行:

// Query
var notifications = await _db.Notifications
    .OrderByDescending(x => x.Timestamp)
    .ProjectTo<NotificationModel>(_mapperConfig)
    .ToListAsync(token);

// Mapping
CreateMap<Notification, NotificationModel>()
    .ForMember(dest => dest.Area, opt => opt.ResolveUsing(src => src.Area));

源和目标模型:

public class Notification
{
    public int Id {get;set;}
    public NotificationArea Area { get; set; }
}

public class NotificationModel
{
    public int Id {get;set;}
    public EnumValue Area {get;set;}
}

我知道我做错了什么......显然......我只是不知道它到底在哪里。我觉得我有 A 和 C 但缺少 B。

标签: c#asp.net-web-apiautomapper

解决方案


推荐阅读