使用 include Entity Framework core 3.1 时如何过滤嵌套对象

Mus*_*med 5 c# entity-framework asp.net-core asp.net-core-3.1 entity-framework-core-3.1

我有一个用户表,其中包含一个名为UserPriviliges的嵌套表,在此表中我有isDeleted字段来识别已删除的数据而不实际删除它,我想使用 include 检索用户及其权限

 public async Task<User> GetUser(Guid userId)
    {
        return await RepositoryContext.Users
            .Include(x => x.UserPrivileges).ThenInclude(x => x.Privilege)
            .FirstOrDefaultAsync(x => x.Id == userId);
    }
Run Code Online (Sandbox Code Playgroud)

如何过滤UserPriviliges以仅包含具有 false isDeleted属性的项目

在 EF Core <3.0 中我可以这样做

 return await RepositoryContext.Users
            .Include(x => x.UserPrivileges.Where(y=>y.IsDeleted)).ThenInclude(x => x.Privilege)
            .FirstOrDefaultAsync(x => x.Id == userId);
Run Code Online (Sandbox Code Playgroud)

但它在 EF Core 3.1 中不再工作,它返回

Include 内使用的 Lambda 表达式无效

her*_*e 0 3

我根本不记得这在 EF Core 中工作过;通常我们会将其分为两个查询:1-获取用户数据,2-获取过滤后的用户权限

var user = await RepositoryContext.Users
    .FirstOrDefaultAsync(u => u.Id == userId);

await RepositoryContext.UserPrivileges
    .Where(up => up.UserId == userId && !up.IsDeleted)
    .Include(up => up.Privilege)
    .ToListAsync();

return user;
Run Code Online (Sandbox Code Playgroud)

当我们通过第二个查询将相关数据引入上下文时,ef 将负责填充 user.UserPrivileges,因此我们根本不需要分配它。如果我们获取多个用户数据,这很有效。