I 've got a simple query but it throws, that it couldn't be translated
here is the function
public async Task<Voucher> Get(Predicate<Voucher> predicate)
{
try
{
var voucher = await _promotionCoreContext.Vouchers.AsNoTracking().FirstOrDefaultAsync(i => predicate(i));
return voucher;
}
catch (Exception ex)
{
_logger.LogError(ex.Message);
}
}
usage is something like this:
repository.Get(c => c.Code == "abc");
but for a reason it can't translate the predicate, it compiles though.
---- System.InvalidOperationException : The LINQ expression 'DbSet() .Where(v => Invoke(__predicate_0, v) )' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to 'AsEnumerable', 'AsAsyncEnumerable', 'ToList', or 'ToListAsync'. See
Anyone know how I can fix this without making it client side with ToList()
CodePudding user response:
The IQueryable.FirstOrDefaultAsync takes an
Expression<Func<TSource,bool>>
, not aFunc<TSource,bool>
. The Enumerable extension methods can work withFunc<TSource,bool>
, but since that's basically a function pointer, EF can't translate it to SQL.