我的问题是将从数据库返回的Linq2Sql对象转换为Viewmodel并进行填充。我们在几个区域中已经完成了这项工作,并且已经制定了一个很好的分层模式,但最新的项目需要使用一些枚举类型,这给我们带来了很多麻烦。目前,我们从数据库中获取数据,然后使用Automapper将数据转换(或展开)到Viewmodels中,但是将枚举类型添加到模型中似乎会导致Automapper出现问题。我尝试创建自定义解析器以满足所有其他映射需求,但在这种情况下无效。
代码示例如下:
我收到了以下错误信息。
我希望在所有映射操作中都使用Automapper,但我看到很多人说它不能做这种类型的映射,所以我开始怀疑我是否使用错误?此外,我看到一些关于ValueInjecter的提及 - 这是Automapper的替代品,还是仅用于填补模型的水分并使用Automapper进行展平?
是的,我可以在我的ViewModel中使用字符串,但我不喜欢魔术字符串,而且这个特定项被助手用于在许多地方执行一些逻辑。
代码示例如下:
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进行展平?
是的,我可以在我的ViewModel中使用字符串,但我不喜欢魔术字符串,而且这个特定项被助手用于在许多地方执行一些逻辑。