Thursday, December 16, 2010

"Local sequence cannot be used in LINQ to SQL implementations of query operators except the Contains operator" - C#

While writing a small code chunk, I faced the following exception "Local sequence cannot be used in LINQ to SQL implementations of query operators except the Contains operator"

The code goes here:

var selectedEmployees = from emp in context.employees                        select emp;List<string> employeeNames = new List<string>{ "Joseph", "Richard"};



var employeesInList = from emp in selectedEmployees                      from empName in employeeNames                      where emp.ename.Contains(empName)                      select emp.ename;foreach (var finalEmp in employeesInList)      Console.WriteLine(finalEmp);






The code does not do anything substantial, but is only an example to demonstrate the problem. It retrieves all employees from a database table and displays only those employees whose names are there in the list "employeeNames"

The exception "Local sequence cannot be used in LINQ to SQL implementations of query operators except the Contains operator" occurs at the "foreach" line.

Reason behind the exception:

If you observe the code, we are joining a LINQ to SQL table with an in-memory list which is not supported by the current functionality. The easiest resolution is to convert the LINQ to SQL table into an IEnumerable list, which can be done as follows:

var employeesInList = from emp in selectedEmployees.AsEnumerable()                      from empName in employeeNames                      where emp.ename.Contains(empName)                      select emp.ename;