首页 > 解决方案 > 在 EF 查询中使用整数列表 - 以可翻译的形式重写查询,或切换到客户端评估

问题描述

使用 Entity Framework Core 3.1 我有以下查询:

    var ids = new List<Int32> { 1, 2, 3 }; 

    users = context.Users

      .Where(x => ids.All(y => x.UserSkills.Any(z => y == z.SkillId)));

    var result = await users.ToListAsync();

当我运行此查询时,我收到以下错误:

'The LINQ expression 'DbSet<User>
    .Where(u => True && __ids_0
        .All(y => DbSet<UserSkill>
            .Where(u0 => EF.Property<Nullable<int>>(u, "Id") != null && EF.Property<Nullable<int>>(u, "Id") == EF.Property<Nullable<int>>(u0, "UserId"))
            .Any(u0 => y == u0.SkillId)))' 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()

我该如何解决这个问题?

标签: entity-framework-coreentity-framework-core-3.1

解决方案


答案是您的错误信息:

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

所以 linq 命令对于实体框架来说是复杂的。您必须编写一个更简单的 linq 命令,例如:

 var users = context.Users.Where(x => x.UserSkills.Any(z => 1 == z.SkillId)).ToListAsync;

但这不是你想要的。所以你必须为客户端而不是数据库编写代码语句。

加载用户,然后在客户端使用您的代码。


推荐阅读