'"An expression tree may not contain a call or invocation that uses optional arguments" in LINQ expression with split string entity?

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

Where, x.deptIds is department ids stored as string separated by comma. Getting erro "An expression tree may not contain a call or invocation that uses optional arguments". How to solve it?



Solution 1:[1]

Just specify an optional parameter. string.Split(",") becomes string.Split(",", System.StringSplitOptions.None)

providing optional parameters to string.Split resolved my error

Solution 2:[2]

As the comments pointed out, storing multiple values in a field is a very bad design choice, so noone should ever get to the point when they have to use String.Split in a Linq.

But to answer your question, you can use String.Contains, String.StarsWith and String.EndsWith, these can be translated to SQL. For example you can write:

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()
    ));

This solution can change depending on where you have spaces around the commas in the database.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 snehakatke
Solution 2 Annosz