Any on enums inside of Where in Entity Framework Core

asp.net-core c# entity-framework entity-framework-core linq

Question

I keep getting Entity Framework errors on this snippet of code (Consistency type is an enum):

IQueryable<Examination> examinationsSet = _context.Examinations;

if (consistency.Length > 0)
{
    examinationsSet = examinationsSet
                          .Where(x => consistency.Any(y => (int)y == (int)x.Consistency));
}

I tried adding AsQueryable or AsEnumerable between consistency and Any, but it doesn't help. This is the main error I am getting:

System.InvalidOperationException: „The LINQ expression 'Where(
source: DbSet,
predicate: (e) => Any(
source: (Unhandled parameter: __consistency_0),
predicate: (y) => (int)y == (int)e.Consistency))'
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 either AsEnumerable(), AsAsyncEnumerable(), ToList(), or ToListAsync().

1
1
9/29/2019 7:12:53 PM

Accepted Answer

When an Entity Framework query executes, it's translated to SQL. It's best to do as much of the logic as possible outside of the query to avoid confusing the translator.

Try something like this instead:

List<int> consistencyNumbers = consistency.Select(item => (int)item).ToList();  
IQueryable<Examination> examinationsSet = consistencyNumbers.Count > 0
    ? _context.Examinations.Where(x => consistencyNumbers.Any(y => y == (int)x.Consistency))
    : _context.Examinations;
2
9/30/2019 3:53:46 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow