Search code examples
linqlinq-to-entitiesiqueryable

Selecting values from IQueryable with IsNullOrWhitespace check


I am trying to do the following with a IQueryable expression:

(from Person p in s
   select new
   {
           label = p.FirstName + " "
       + (string.IsNullOrWhiteSpace(p.MiddleName) ? p.MiddleName + " " : "")
                   + p.LastName,
       value = p.Id
       }).ToList();

I am getting following error:

LINQ to Entities does not recognize the method 'Boolean 
IsNullOrWhiteSpace(System.String)' method, and this method cannot be 
translated into a store expression.

What is the solution for this?


Solution

  • String.IsNullOrWhitespace is a static function of the string object and cannot be used with Entity Framework queries, whereas p.FirstName.StartsWith("S") is a method of the entity property and can be used.

    To answer your question you will have to roll your own inline. Try this:

    (from Person p in s
       select new
       {
           label = p.FirstName + " "
           + ((p.MiddleName != null && p.MiddleName != string.Empty) ? p.MiddleName + " " : "")
                       + p.LastName,
           value = p.Id
       }).ToList();