【问题标题】:Perform filter through bridging table using Ef Core使用 Ef Core 通过桥接表执行过滤
【发布时间】:2020-10-12 08:57:31
【问题描述】:

我有三个模型:

public class User
{
    public long Id { get; set; }
    public string Name { get; set; }
    public ICollection<UserRole> UserRole { get; set; }
}

public class Role
{
    public long Id { get; set; }
    public long Title { get; set; }
    public ICollection<UserRole> UserRole { get; set; }
}

public class UserRole
{
    public long Id { get; set; }
    public User user { get; set; }
    public Role role { get; set; }
}

现在我有一种情况,我必须根据某个角色获取用户列表,基本上我必须根据 roleId 过滤用户。如何使用 ef core Linq 查询来实现这一点。

我尝试了以下查询,但它不能转换为 SQL。

context.User.Include(it => it.UserRole)
    .ThenInclude(it => it.Role)
    .Where(it => it.UserRole.Contains(new Role { Id = 1 }))
    .ToListAsync();

【问题讨论】:

    标签: c# .net entity-framework asp.net-core entity-framework-core


    【解决方案1】:

    我尝试了以下查询,但它不能转换为 SQL

    如果这能编译,我会感到惊讶:

    it.UserRole.Contains(new Role { Id = 1 })
    

    it.UserRoleICollection&lt;UserRole&gt; 类型,所以 Contains 需要 UserRole 参数

    要检查 ID = 1 的 Role,您可以尝试使用 Any 而不是 Contains

    context.User.Include(it => it.UserRole)
        .ThenInclude(it => it.Role)
        .Where(it => it.UserRole.Any(ur => ur.Role.Id == 1))
        .ToListAsync();
    

    【讨论】:

    • 谢谢!有效。我确实有一个问题,为什么 contains() 不起作用而 any() 起作用?
    • Contains 需要UserRole,而不是Role。您也许可以像这样使用Containsit.UserRole.Contains(context.UserRoles.Single(ur =&gt; ur.Role.Id == 1))
    猜你喜欢
    • 2019-04-02
    • 2022-01-08
    • 2020-10-19
    • 1970-01-01
    • 2016-09-29
    • 2020-01-21
    • 1970-01-01
    • 2021-04-16
    • 2021-10-13
    相关资源
    最近更新 更多