I have the below code:
var countries = from c in db.Countries
where (string.IsNullOrWhiteSpace(searchAlpha2) || (c.Alpha2 ?? string.Empty).ToUpper().Contains(searchAlpha2.ToUpper()))
&& (string.IsNullOrWhiteSpace(searchAlpha2) || (c.Alpha3 ?? string.Empty).ToUpper().Contains(searchAlpha3.ToUpper()))
&& (string.IsNullOrWhiteSpace(searchName) || (c.Name ?? string.Empty).ToUpper().Contains(searchName.ToUpper()))
select c;
This code uses Entity Framework v6 Code First over a SQL database.
Aside from performance, if I don't include the IsNullOrWhitespace
I get no results when the filter criteria are blank (I've tested both null and blank values); however when a value is present this works as expected.
I'm getting the error:
LINQ to Entities does not recognize the method 'Boolean IsNullOrWhiteSpace(System.String)' method, and this method cannot be translated into a store expression.
I'm trying to use the searchXXX strings to filter on columns. I've tried using RegEx.IsMatch, SqlMethods.Like, and the code below, but all give me errors saying those functions are not allowed (errors come from either EntityFramework.SqlServer
or from Linq to Entities
). I've seen numerous posts on here where this has been done successfully though - so wonder if I'm missing something fundamental?
LINQ to Entities does not recognize the method System.String ToString () method, and this method cannot be translated into a store expression. In following code snippet, a LINQ to SQL query is executed on the records returned from the Entity Framework.
LINQ to Entities does not recognize the method System.String ToString () method, and this method cannot be translated into a store expression. In this article I will explain with an example, how to solve the following error (exception) when using LINQ to SQL or Lamba expressions on DbSet records returned by Entity Framework in C# .Net.
This exception mainly occurs when we query SQL database using entity framework. The problem is that you are calling ToString in a LINQ to Entities query (IQueryable to IEnumrable). That means the parser is trying to convert the ToString call into its equivalent SQL (which isn't possible...hence the exception).
This exception occurs because LINQ to SQL query internally builds an SQL query and executes it on the database directly and hence when one tries to use the ToString method which is a .Net data type conversion method and cannot be used for an SQL Query. 1. StringConvert method
If you want to use your statement in current form you might want to replace
string.IsNullOrWhiteSpace(searchAlpha2)
to
!(searchAlpha2 == null || searchAlpha2.Trim() == string.Empty)
and all the other values too, for it to get translated to working SQL.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With