加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – 使用Automapper将字符串映射到枚举

发布时间:2020-12-16 04:37:27 所属栏目:asp.Net 来源:网络整理
导读:我的问题是从已从数据库返回的 Linq2Sql对象中保护Viewmodel.我们已经在一些领域做到了这一点并且有一个很好的分层模式,但是最新的项目要求使用一些枚举,这引起了全面的麻烦.目前我们从数据库中撤回然后使用Automapper来水合(或展平)到我们的View模型中,但是
我的问题是从已从数据库返回的 Linq2Sql对象中保护Viewmodel.我们已经在一些领域做到了这一点并且有一个很好的分层模式,但是最新的项目要求使用一些枚举,这引起了全面的麻烦.目前我们从数据库中撤回然后使用Automapper来水合(或展平)到我们的View模型中,但是模型中的枚举似乎导致了Automapper的问题.我已经尝试创建自定义resovler,它已满足我所有其他映射要求,但它在这个实例中不起作用.

代码示例如下:

public class CustomerBillingTabView{
    public string PaymentMethod {get; set;}
    ...other details
}

public class BillingViewModel{
    public PaymentMethodType PaymentMethod {get; set;}
    ...other details
}

public enum PaymentMethodType {
    Invoice,DirectDebit,CreditCard,Other
}

public class PaymentMethodTypeResolver : ValueResolver<CustomerBillingTabView,PaymentMethodType>
{
    protected override PaymentMethodType ResolveCore(CustomerBillingTabView source)
    {

        if (string.IsNullOrWhiteSpace(source.PaymentMethod))
        {
            source.PaymentMethod = source.PaymentMethod.Replace(" ","");
            return (PaymentMethodType)Enum.Parse(typeof(PaymentMethodType),source.PaymentMethod,true);
        }

        return PaymentMethodType.Other;
    }
}

        CreateMap<CustomerBillingTabView,CustomerBillingViewModel>()
        .ForMember(c => c.CollectionMethod,opt => opt.ResolveUsing<PaymentMethodTypeResolver>())

我收到以下错误

[ArgumentException: Type provided must be an Enum.
Parameter name: enumType]
   System.Enum.TryParseEnum(Type enumType,String value,Boolean ignoreCase,EnumResult& parseResult) +9626766
   System.Enum.Parse(Type enumType,Boolean ignoreCase) +80
   AutoMapper.Mappers.EnumMapper.Map(ResolutionContext context,IMappingEngineRunner mapper) +231
   AutoMapper.MappingEngine.AutoMapper.IMappingEngineRunner.Map(ResolutionContext context) +720

我想坚持使用Automapper进行所有的映射操作,但是我看到很多人说它没有做这种类型的映射,所以我开始怀疑我是否在错误中使用它办法?另外,我已经看过一些关于ValueInjecter的提及 – 这是Automapper的替代方案,还是只是插入Automapper中的漏洞来模拟水化并使用Automapper进行展平?

是的,我可以在我的ViewModel中使用一个字符串,但我不是魔术字符串的粉丝,帮助者使用这个特殊项目在许多地方执行某些逻辑.

解决方法

这是AutoMapper文档的一个问题.如果您下载AutoMapper源,那里有一些示例.您想要的代码如下所示:
public class PaymentMethodTypeResolver : ValueResolver<CustomerBillingTabView,PaymentMethodType>
{
    protected override PaymentMethodType ResolveCore(CustomerBillingTabView source)
    {

        string paymentMethod = source.Context.SourceValue as string;

        if (string.IsNullOrWhiteSpace(paymentMethod))
        {
            paymentMethod  = paymentMethod.Replace(" ","");
            return source.New((PaymentMethodType)Enum.Parse(typeof(PaymentMethodType),paymentMethod,true));
        }

        return source.New(PaymentMethodType.Other);
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读