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

Extension method & LINQ to Entities does not recognize the method error

在尝试将实体映射到 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
             });