gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 03:32:44 24 4
gpt4 key购买 nike

我的问题是从数据库返回的 Linq2Sql 对象中提取 Viewmodel。我们已经在几个领域做到了这一点,并为此制定了一个很好的分层模式,但最新的项目要求使用一些枚举,这引起了全面的头痛。目前,我们从数据库中撤回,然后使用 Automapper 水合(或展平)到我们的 Viewmodel 中,但模型中的枚举似乎会导致 Automapper 出现问题。我尝试创建自定义解析器,它足以满足我所有其他映射要求,但在这种情况下不起作用。

代码示例如下:

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, String value, 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);
}
}

关于asp.net-mvc - 使用 Automapper 将字符串映射到枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3752141/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com