带有 IN 列表的动态 Linq

问题描述

我正在使用 EF Dynamic Linq 库根据用户输入构建动态查询

我能够像这样设置 where 子句来搜索 User Roles = 1:

            var users = await _db.Users.Include(x => x.UserRoles).ThenInclude(x => x.Role)
            .Where(x => x.IsActive == true) 
            .Where("x => x.UserRoles.Any(y => y.RoleId == 1)")

在此查询中,角色 ID“1”来自另一个来源,例如用户输入。如何修改查询搜索多个角色 ID?传入的字符串值类似于“1,2,4”。如何在搜索中使用此字符串来查找具有任何角色的所有用户?我尝试使用 new []{1,4} 之类的东西,但不确定如何将其放入字符串中。

解决方法

int[] roles = new int[] { 1,2,3 };
IEnumerable<User> users = await db.Users
    .Include(x => x.UserRoles)
    .ThenInclude(x => x.Role)
    .Where(x => x.IsActive == true && x.UserRoles.Any(y => roles.Contains(y)));