带有拆分字符串实体的LINQ表达式中的“表达式树可能不包含使用可选参数的调用或调用”?

问题描述

var list1 = _context.Employees.Where(x=> x.EmployeeId.Equals(empId)
                    && **x.deptIds.Split(",")**.ToList().Any(p => (p!=(deptId.ToString()))));

其中,x.deptIds是存储为字符串的部门ID(用逗号分隔)。 出现错误“表达式树可能不包含使用可选参数的调用调用”。如何解决

解决方法

正如评论所指出的那样,将多个值存储在一个字段中是一个非常糟糕的设计选择,因此,当他们必须在Linq中使用String.Split时,谁也没人管。

但是要回答您的问题,可以使用String.ContainsString.StarsWithString.EndsWith,它们可以转换为SQL。例如,您可以编写:

var list1 = _context.Employees.Where(x=> x.EmployeeId.Equals(empId)
    && (x.deptIds.Contains("," + deptId.ToString() + ",") 
        || x.deptIds.StartsWith(deptId.ToString() + ",") 
        || x.deptIds.EndsWith("," + deptId.ToString()
    ));

此解决方案可能会有所不同,具体取决于数据库中逗号周围的空格。

,

只需指定一个可选参数即可。 string.Split(",") 变成 string.Split(",",System.StringSplitOptions.None)