gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 20:16:31 25 4
gpt4 key购买 nike

我有一个 user 表,其中包含一个名为 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);
}

如何过滤UserPriviliges以仅引入具有错误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);

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

Lambda expression used inside Include is not valid

最佳答案

我根本不记得这在 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;

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

关于c# - 使用 include Entity Framework core 3.1 时如何过滤嵌套对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60083297/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com