c# - 扩展方法 & LINQ to Entities 无法识别方法错误

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

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

LINQ to Entities does not recognize the method 'Dto.Team ToTeamDto(Team, System.String)' method, and this method cannot be translated into a store expression."

这是查询

 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
            };
        }

这有什么问题吗? 我该如何修复它?

最佳答案

问题是 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
             });

关于c# - 扩展方法 & LINQ to Entities 无法识别方法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42741529/

相关文章:

c# - 使用 EF4 如何跟踪记录作为 Skip().Take() 结果集的一部分的次数

c# - 是否可以防止 Entity Framework 4 覆盖自定义属性?

c# - 将多个 EF 上下文注册到一个 DI 容器中

c# - 复杂的 LINQ 分页算法

c# - 如果用户定义函数的静态调用顺序违反了一些规则,让编译器提示

entity-framework - 使用 Entity Framework 刷新数据

c# - Entity Framework - 有条件地将列添加到分组依据中

c# - 是否可以在 AutoFixture SemanticComparison 中为指定类型设置自定义比较器

c# - 从字符数组中删除一个字母

c# - HTTP header 中内容处置的替代方案 (c#)