Sisyphus Sisyphus - 8 months ago 52
SQL Question

EF could not translate expression to sql

It looks like EF is not able to translate the express in the following code, this is the call

Counter lastCounter = unitOfWork.CounterRepository.FindLast(x => x.Div == counter.Div, x => x.Div);


this is the method

public Counter FindLast(Expression<Func<Counter, bool>> predicate, params Expression<Func<Counter, object>>[] includedProperties)
{
IQueryable<Counter> set = context.Set<Counter>().Where(predicate);

foreach (var includeProperty in includedProperties)
{
set = set.Include(includeProperty);
}
return set.Last();
}


Any idea what could be the problem?

Answer Source

It's quite simple, really: Entity Framework just does not support Last(). The reason for this is that in SQL, you also cannot select the last element (i.e. you have SELECT TOP but don't have SELECT BOTTOM).

See https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/ef/language-reference/supported-and-unsupported-linq-methods-linq-to-entities

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download