"ef core “group by could not be translated and will be evaluated locally.”" Code Answer


the problem is that when you're trying to group in the database, you don't really have the means to materialize values inside a group. you only get to select grouped columns or aggregated values (via sum, etc.) of non-grouped columns.

for example:

select [h].[date], [h].[username]
from [holidays] as [h]

this query would produce result set of which every row would have two columns, date and name.

let's try grouping though:

select [h].[date], [h].[username]
from [holidays] as [h]
group by [h.date]

this sql query wouldn't be evaluated at all because it's invalid from sql server perspective. error message would be

column 'holidays.username' is invalid in the select list because it is not contained in either an aggregate function or the group by clause.

summing all this up, you can either do what @ercan tirman has suggested, or, load all the usernames and dates and group them in-memory:

var dateandusername = await _dbcontext.holidays
    .select(x => new {x.date, x.username})

dictionary<datetime, list<string>> grouped = dateandusername
    .groupby(x => x.date)
    .todictionary(x => x.key, x => x.select(y => y.username).tolist());
By danh on January 2 2022

Answers related to “ef core “group by could not be translated and will be evaluated locally.””

Only authorized users can answer the Search term. Please sign in first, or register a free account.