OrElse OrElse - 1 year ago 47
C# Question

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

While trying to map an entity to an DTO i get the following error.

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."

Here is the query

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

and the extension method

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

What is wrong with this one?
How can i fix it?

Answer Source

The problem is that EF cannot translate your function into SQL. The easiest solution is to materialise the data with ToList then use your function:

var source = db.Standings
             .Where(c => c.LeagueID == leagueId)
             .Select(c => new Standing
                 id = c.id,
                 team = includeTeam ? c.Team.ToTeamDto("en-US") : null,
                 //other properties here
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download