I'm writing a simple search query for my Entity Framework application. I need to check if a bunch of fields are null, and if not, call ToLower() on them and compare to the search query. The LINQ query looks something like this:
public IQueryable<Store> SearchStores(string q, IQueryable<Store> source)
{
q = q.ToLower();
return (
from s in source
where (
(s.Name != null && s.Name.ToLower().Contains(q)) ||
(s.Description != null && s.Description.ToLower().Contains(q)) ||
...
}
There are a lot of lines like this, so I was tempted to write a helper method to clean it up a bit:
public static bool SafeSearch(this string s, string q)
{
return s == null ? false : s.ToLower().Contains(q);
}
This of course doesn't work, though, since LINQ to entities doesn't understand what the SafeSearch function is:
LINQ to Entities does not recognize the method 'Boolean SafeSearch(System.String, System.String)' method, and this method cannot be translated into a store expression.
Is there an easy way to write a simple custom function like this?
Thanks!
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…