【问题标题】:LINQ to Entities does not recognize the method 'System.Object InjectFrom(System.Object, System.Object[])' [duplicate]LINQ to Entities 无法识别方法'System.Object InjectFrom(System.Object, System.Object[])' [重复]
【发布时间】:2016-01-08 09:25:36
【问题描述】:

我有以下代码,可以正常工作且符合预期:

return profileEntities.Select(x => (ProfileDTO)new ProfileDTO()
        {
            Localizations = new List<ProfileLocalizationDTO>()
        }
        .InjectFrom(x)).ToList();

但是,我想更进一步,用来自 repo 的值填充 Localizations,如下所示:

return profileEntities.Select(x => (ProfileDTO)new ProfileDTO()
        {
            Localizations = _repoProfileLocalization
                                .Query(y => y.ProfileId == x.Id)
                                .Select(y => (ProfileLocalizationDTO)new ProfileLocalizationDTO().InjectFrom(y))
                                .ToList()
        }
        .InjectFrom(x)).ToList();

这会引发错误

“System.NotSupportedException”类型的异常发生在 EntityFramework.SqlServer.dll 但未在用户代码中处理

附加信息:LINQ to Entities 无法识别该方法 'System.Object InjectFrom(System.Object, System.Object[])' 方法,以及 此方法无法转换为商店表达式。

非常感谢任何建议。

【问题讨论】:

    标签: c# entity-framework linq


    【解决方案1】:

    对于第二个版本,您必须在 Select 中调用 AsEnumerable() 来告诉 clr 方法 InjectFrom 将在内存中执行。

    return profileEntities.Select(x => (ProfileDTO)new ProfileDTO()
        {
          Localizations = _repoProfileLocalization
                              .Query(y => y.ProfileId == x.Id)
                              .AsEnumerable()
                              .Select(y => (ProfileLocalizationDTO)new ProfileLocalizationDTO()
                                          .InjectFrom(y))
                              .ToList()
        }
        .InjectFrom(x)).ToList();
    

    在您的第一个示例中,因为您在 select 中实例化了一个通用 List,所以您将在 select 之后将所有结果保存在内存中,因为 Linq 无法在数据库上执行它。在第二个示例中,Linq 仍然尝试在 select 中对数据库执行所有操作,但随后您调用了一个无法转换为 sql 的方法并收到错误。

    【讨论】:

    • 成功了!谢谢!
    猜你喜欢
    • 2012-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多