Entity Framework LINQ to Entities does not recognize the method exception
Exception: LINQ to Entities does not recognize the method
It is the most common exception occurs when working with entity framework and converting data inside IQueryable result for filtering.
using (var context = new CustomerContext()) { var item = context.InvoiceItems .Where(i => i.Code == code.ToString()) .FirstOrDefault(); }
StackOverflow Related Questions
- Why LINQ to Entities does not recognize the method 'System.String ToString()?
- LINQ to Entities does not recognize the method 'System.String Format(System.String, System.Object, System.Object)'
- LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression
Solution
There are different solutions for this specific problem.
Move ToString() call to a separate line.
using (var context = new CustomerContext()) { string codeStr = code.ToString(); var item = context.InvoiceItems .Where(i => i.Code == codeStr) .FirstOrDefault(); }
Use EF Extension Method,
using (var context = new CustomerContext()) { var item = context.InvoiceItems .Where(i => i.Code == SqlFunctions.StringConvert(code)) .FirstOrDefault(); }
Convert IQueryable result to IEnumerable before Filtering
using (var context = new CustomerContext()) { var item = context.InvoiceItems.AsEnumerable() .Where(i => i.Code == code.ToString()) .FirstOrDefault(); }
ZZZ Projects