在单元测试中模拟我的自动映射器时,我收到“无法将类型 'PlanEntity' 转换为 'TDestination'”编译时错误。
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;
谁能帮我解决这个问题?
最佳答案
var value = source as PlanEntity
正在将源分配给“值”变量。但是,您稍后尝试将其转换为目标类型 - return (TDestination)value;
这些类型会有所不同,从而导致您的错误。
在您的第一个代码块中,您需要添加以下内容以使其等效于第二个代码块:
var planModel = new PlanModel() { Id = value.Id };
return (TDestination)planModel;
关于c# - Automapper 无法转换为类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44368517/