C# 自动映射无法转换为类型
在单元测试中模拟我的自动映射程序时,我遇到了“无法将类型‘PlanEntity’转换为‘TDestination’”的编译时错误C# 自动映射无法转换为类型,c#,compiler-errors,automapper,C#,Compiler Errors,Automapper,在单元测试中模拟我的自动映射程序时,我遇到了“无法将类型‘PlanEntity’转换为‘TDestination’”的编译时错误 public TDestination Map<TSource, TDestination>(TSource source) where TDestination : class { var value = source as PlanEntity; if (value
public TDestination Map<TSource, TDestination>(TSource source) where TDestination : class
{
var value = source as PlanEntity;
if (value != null)
{
return (TDestination)value;
}
return null;
}
publictdestination映射(TSource-source),其中tddestination:class
{
var值=源作为行星度;
if(值!=null)
{
返回(TDestination)值;
}
返回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;
}
publictdestination映射(对象源),其中tddestination:class
{
var值=源为IEnumerable;
if(值!=null)
{
变量结果=值。选择(i=>
新平面模型
{
Id=i.Id,
Name=i.名称
});
返回(TDestination)结果;
}
返回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;
}
publictdestination映射(TSource-source),其中tddestination:class
{
var值=源作为行星度;
if(值!=null)
{
var planModel=新的planModel
{
Id=value.Id,
Name=value.Name
};
返回(TDestination)平面模型;
}
返回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;
TDestination映射(TSource-source),其中TDestination:class;
TDestination映射(TSource source,TDestination destination destination),其中TDestination:class;
TDestination映射(对象源),其中TDestination:class;
有人能帮我解决这个问题吗?
var value=source,因为PlanEntity正在将源分配给“value”变量。但是,您稍后尝试将其强制转换为目标类型-return(tdestinition)值代码>这些类型将不同,从而导致错误
在第一个代码块中,需要添加以下内容,使其与第二个代码块等效:
var planModel = new PlanModel() { Id = value.Id };
return (TDestination)planModel;
TDestination只不过是我的PlanModel,所以最终的返回语句在运行时(PlanModel)planEntity应该是这样的。它应该可以很好地工作,就像在第二种方法中收集行星一样。除非PlanModel
继承自plantentity
,否则该转换将无法工作。您的第二个代码块正在将PlanModel
转换为TDestination
类型,大概是PlanModel
@S7H我已经更新了我的答案,说明了如何使第一个代码块与第二个代码块等效。我明白您的意思。您正在将PlanEntity转换为PlanModel。但是.Select不会对值起作用,因为它是单个对象而不是对象的集合。我已经试着用另一种方式来做了。但它给出了相同的误差,唯一的区别是现在用平面模型代替了行星度。“无法将类型‘PlanModel’转换为‘TDestination’”,我注意到了这一点,并更新了答案。您如何在单元测试中使用Map方法?