2017-06-05 55 views
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类有三个覆盖。

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; 

任何人都可以帮我解决这个问题吗?

回答

0

var value = source as PlanEntity将源赋值给'value'变量。但是,您稍后尝试将其转换为目标类型 - return (TDestination)value;这些类型将会不同,从而导致您的错误。

在你的第一个代码块,你将需要添加以下,使其等效为第二代码块:

var planModel = new PlanModel() { Id = value.Id }; 
return (TDestination)planModel; 
+0

TDestination是什么,但我PlanModel所以最终return语句应该是这样的,在运行时(PlanModel)planEntity。它应该像第二种方法中的PlanEntity集合一样工作。 – S7H

+0

除非'PlanModel'继承自'PlanEntity',否则转换将不起作用。你的第二个代码块将'PlanModel'强制转换为'TDestination'类型,推测它是'PlanModel'。 – ZippyZippedUp

+0

@ S7H我已经更新了我的答案,展示了如何使第一个代码块等于第二个代码块。 – ZippyZippedUp

相关问题