0
ユニットテストでオートマッパーをモックしながら「PlanEntityタイプを 'TDestination'に変換できません」コンパイル時エラーが発生しました。Automapperがタイプに変換できません
public TDestination Map<TSource, TDestination>(TSource source) where TDestination : class
{
var value = source as PlanEntity;
if (value != null)
{
return (TDestination)value;
}
return null;
}
しかし、IEnumerableをマップするとうまく動作しています。
public TDestination Map<TDestination>(object source) where TDestination : class
{
var value = source as IEnumerable<PlanEntity>;
if (value != null)
{
var results = value.Select(i =>
new PlanModel
{
Id = i.Id,
Name = i.Name
});
return (TDestination)results;
}
return null;
}
これもやってみましたが、同じエラーが発生しています。
public TDestination Map<TSource, TDestination>(TSource source) where TDestination : class
{
var value = source as PlanEntity;
if (value != null)
{
var planModel = new PlanModel
{
Id = value.Id,
Name = value.Name
};
return (TDestination)planModel;
}
return null;
}
私のmockMapperクラスには3つのオーバーライドがあります。
TDestination Map<TSource, TDestination>(TSource source) where TDestination : class;
TDestination Map<TSource, TDestination>(TSource source, TDestination destination) where TDestination : class;
TDestination Map<TDestination>(object source) where TDestination : class;
誰もが私を助けることができますか?
TDestinationは私PlanModel以外の何ものでもありません(PlanModel)planEntity。 2番目の方法でPlanEntityのコレクションのために働いているようにうまくいくはずです。 – S7H
'PlanModel'が' PlanEntity'から継承しない限り、キャストは機能しません。あなたの2番目のコードブロックは 'PlanModel'を' TDestination'型にキャストしています。これは 'PlanModel'でしょう。 – ZippyZippedUp
@ S7H私は最初のコードブロックを2番目のコードブロックに等しくする方法を示す答えを更新しました。 – ZippyZippedUp