【问题标题】:Extension method & LINQ to Entities does not recognize the method error扩展方法 & LINQ to Entities 无法识别方法错误
【发布时间】:2017-08-02 03:56:46
【问题描述】:

尝试将实体映射到 DTO 时,出现以下错误。

LINQ to Entities 无法识别方法 'Dto.Team ToTeamDto(Team, System.String)' 方法,而该方法不能 翻译成商店表达式。”

这里是查询

 bool includeTeam = true;

 var source = from c in db.Standings
                         where c.LeagueID == leagueId
                         select new Standing
                         {
                             id = c.StandingsId,
                             team = includeTeam ? c.Team.ToTeamDto("en-US") : null
                         };

以及扩展方法

        internal static Dto.Team ToTeamDto(this Team team, string locale)
        {
            return new Dto.Team
            {
                id = team.TeamID,
                name = team.name
            };
        }

这个有什么问题吗? 我该如何解决?

【问题讨论】:

    标签: c# entity-framework linq extension-methods dto


    【解决方案1】:

    问题在于 EF 无法将您的函数转换为 SQL。最简单的解决方案是使用 ToList 实现数据,然后使用您的函数:

    var source = db.Standings
                 .Where(c => c.LeagueID == leagueId)
                 .ToList()
                 .Select(c => new Standing
                 {
                     id = c.id,
                     team = includeTeam ? c.Team.ToTeamDto("en-US") : null,
                     //other properties here
                 });
    

    【讨论】:

    • 一定有比这更简单的解决方法吗?我的意思是,Standing 类有 30 多个属性,为简单起见从上面的示例中排除
    • 您不能将 ToTeamDto 方法传递给 EF 查询。您可以将该代码嵌入到查询中。
    • 我已经简化了一点
    • 我的第一个实现是将查询嵌入到 EF 查询中。我的第二个想法是使用扩展方法,因为其他查询也可能使用这个方法。但是当我读到你的第一条评论时,我说哦,我的……我有 30 多个问题。它现在就像一个魅力!谢谢!
    猜你喜欢
    • 1970-01-01
    • 2014-11-16
    • 2013-06-04
    • 1970-01-01
    • 1970-01-01
    • 2014-08-09
    • 1970-01-01
    • 2012-04-03
    • 2021-11-06
    相关资源
    最近更新 更多