简体   繁体   English

Any on enums inside Where in Entity Framework Core

[英]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.我尝试在一致性和Any之间添加AsQueryableAsEnumerable ,但这没有帮助。 This is the main error I am getting:这是我得到的主要错误:

System.InvalidOperationException: „The LINQ expression 'Where( System.InvalidOperationException:“LINQ 表达式“在哪里(
source: DbSet,来源:数据库集,
predicate: (e) => Any(谓词:(e) => Any(
source: (Unhandled parameter: __consistency_0),来源:(未处理的参数:__consistency_0),
predicate: (y) => (int)y == (int)e.Consistency))'谓词:(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().以可翻译的形式重写查询,或通过插入对 AsEnumerable()、AsAsyncEnumerable()、ToList() 或 ToListAsync() 的调用显式切换到客户端评估。

When an Entity Framework query executes, it's translated to SQL.当实体框架查询执行时,它被转换为 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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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