c# - Automapper 无法转换为类型

标签 c# compiler-errors automapper

在单元测试中模拟我的自动映射器时,我收到“无法将类型 '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/

相关文章:

c# - 如何使用 C# 将 json 插入到 cosmos db 集合中

c# - 如何使用 Automapper 将对象映射到未知目标类型?

c# - 如何覆盖单个自动映射器属性映射?

c# - 如何使用 C# 在 MS Excel 单元格中添加数字验证

c# - EF Core 从多重数为零或一的模型中获取实体的导航属性

c# - Dictionary <字符串,字符串[]>无法将类型 'string[]'隐式转换为 'string'

c++ - 解决由于类之间的循环依赖而导致的构建错误

ios - Xamarin iOS 链接器导致 AutoMapper 问题

c# - 一个窗口窗体中的两个数据 GridView = 无法将数据保存到第二个数据 GridView

java - 错误: Could not find or load main class