私の問題は、データベースから返されたLinq2Sqlオブジェクトからビューモデルをハイドレイトすることです。私たちはいくつかの分野でこれを行い、それのために素晴らしいレイヤードパターンを作り上げましたが、最新のアイテムはいくつかの列挙型を使用する必要があり、これは全体的に頭痛の種を引き起こしました。現在、データベースからプルバックし、Automapperを使用してViewmodelにハイドレイト(またはフラット化)しますが、モデルに列挙型があると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, 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で文字列を使用することもできますが、私はマジックストリングのファンではありません。この特定のアイテムは、ヘルパーがさまざまな場所でロジックを実行するために使用します。