简体   繁体   中英

Any on enums inside of Where in Entity Framework Core

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().

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM