我的问题是从已从数据库返回的
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); } }
原文地址:https://www.jb51.cc/aspnet/248864.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。