String.Isnullorwhitespace in Linq Expression

String.IsNullOrWhiteSpace in LINQ Expression

You need to replace

!string.IsNullOrWhiteSpace(b.Diameter)

with

!(b.Diameter == null || b.Diameter.Trim() == string.Empty)

For Linq to Entities this gets translated into:

DECLARE @p0 VarChar(1000) = ''
...
WHERE NOT (([t0].[Diameter] IS NULL) OR (LTRIM(RTRIM([t0].[Diameter])) = @p0))

and for Linq to SQL almost but not quite the same

DECLARE @p0 NVarChar(1000) = ''
...
WHERE NOT (LTRIM(RTRIM([t0].[TypeName])) = @p0)

Why can LINQ not translate string.IsNullOrWhiteSpace()?

You are using "Linq to Entites", likely either Entity Framework or Linq2Sql. When using Linq to Entites your linq statement is turned in to a expression, parsed, then is converted in to a SQL query. The problem you are having is as simple as the person who wrote the "parse" step did not support string.IsNullOrWhiteSpace in the parser so it does not know how to turn that function in to a SQL string.

You must either use the long form like you showed or update to a newer version of your library that supports it. It appears that the version on GitHub of Entity Framework 6 does IsNullOrEmpty, perhaps you could create a new method of IsNullOrWhitespace and do a request to get it merged in.

LINQ to Entities does not recognize the method IsNullOrWhiteSpace

I would suggest a different approach - use the ability to build queries up on the fly, and thus avoid passing optional query parameters to the expressions altogether - this will result in improved query plans when parsed to sql and executed on the database.

Also, if your database (?SqlServer) is not set to case sensitive collation (i.e. xx_CI_xx), you can avoid the casing conversion as well, as it is redundant:

var myQueryable = db.Countries.AsQueryable();

if (!string.IsNullOrWhiteSpace(searchAlpha2))
{
myQueryable = myQueryable.Where(c => c.Alpha2.Contains(searchAlpha2));
}
...

var countries = myQueryable.ToList();

You can get this and a bunch more functionality using PredicateBuilder

Update

JB: based on StuartLC's answer, here's the code amended to use PredicateBuilder:

var predicate = PredicateBuilder.True<Country>();
if (!string.IsNullOrWhiteSpace(searchAlpha2))
predicate = predicate.And(c => c.Alpha2 != null ? c.Alpha2.Contains(searchAlpha2) : false);
if (!string.IsNullOrWhiteSpace(searchAlpha3))
predicate = predicate.And(c => c.Alpha3 != null ? c.Alpha3.Contains(searchAlpha3) : false);
if (!string.IsNullOrWhiteSpace(searchName))
predicate = predicate.And(c => c.Name != null ? c.Name.Contains(searchName) : false);

IQueryable<Country> countries = db.Countries.AsExpandable().Where(predicate);

Selecting values from IQueryable with IsNullOrWhitespace check

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();

LINQ to Entities does not recognize the method 'System.String IfNullOrWhiteSpace'

IfNullOrWhiteSpace is a custom extension method, so the L2E provider does not know what to do with it.

You don't need to do any null checks when doing a Contains in L2E, so you can just remove the IfNullOrWhiteSpace part.

Creating dynamic Linq Expression using String.IsNullOrEmpty(string) and Nhibernate

I am simply not sure what you are trying to achieve here. The dynamic expression query language is already there: it is the built-in LINQ provider. But let's try to give you more information about its implementation.

When the built-in Linq provider recieves the query, represented by expressions tree, a visitor pattern is used for its conversion into the SQL (with a middle HQL step). One powerful part is the method inspection represented by interface IHqlGeneratorForMethod

public interface IHqlGeneratorForMethod
{
IEnumerable<MethodInfo> SupportedMethods { get; }
HqlTreeNode BuildHql(MethodInfo method, Expression targetObject
, ReadOnlyCollection<Expression> arguments, HqlTreeBuilder treeBuilder
, IHqlExpressionVisitor visitor);
}

The important part here is a set of implementors:

DictionaryItemGenerator
DictionaryContainsKeyGenerator
EqualsGenerator
BoolEqualsGenerator
MathGenerator
AnyHqlGenerator
AllHqlGenerator
MinHqlGenerator
MaxHqlGenerator
CollectionContainsGenerator
HqlGeneratorForExtensionMethod
StartsWithGenerator // StartsWith
EndsWithGenerator // EndsWith
ContainsGenerator // Contains
ToLowerGenerator
ToUpperGenerator
SubStringGenerator
IndexOfGenerator
ReplaceGenerator
TrimGenerator

As you can see, there are the responsibles for Contains, EndsWith and StartsWith. But IsNullOrEmpty cannot be found there.

Other words, regardless what you are doing in a global, your IsNullOrEmpty should end up in a statement like this:

.Where(x => x.MyProperty == null || x.MyProperty == "")

String.IsNullOrEmpty in LINQ To SQL query?

Curiously, per MSDN String.IsNullOrEmpty is supported (by virtue of it not being unsupported), yet I can only find complaints about it not being supported.

However, if it does work you should not explicitly compare it to a boolean value, instead:

var results = from result in context.Records
/*XXX broke :( where !String.IsNullOrEmpty(result.Info) */
where !(result.Info == null || result.Info.Equals(""))
select result;

How to check for null and empty string in Exression.Constant?

As I answered in your previous question.

var parameter = Expression.Parameter(typeof(MyModel), "x");
var body = Expression.PropertyOrField(parameter, nameof(MyModel.Property1));
var methodCall = Expression.Call(typeof(string), nameof(string.IsNullOrWhiteSpace), null, body);
var nullOrWhiteSpaceComparison = Expression.Not(methodCall);
var lambda = Expression.Lambda<Func<MyModel, bool>>(nullOrWhiteSpaceComparison, parameter);

Use it as:

query.Where(lambda);

Ignore Null and Empty string match in Linq Query

You could add && (string.IsNullOrEmpty(o.MulDivFlg) != string.IsNullOrEmpty(lstExchgMatch[0].MulDivFlg)) condition in your Any lambda expression:

var tMisMatchList = lstExchgMatch.Any(o => o.MulDivFlg != lstExchgMatch[0].MulDivFlg &&
(string.IsNullOrEmpty(o.MulDivFlg) != string.IsNullOrEmpty(lstExchgMatch[0].MulDivFlg)));

LINQ syntax where string value is not null or empty

http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=367077

Problem Statement
It's possible to write LINQ to SQL that gets all rows that have either null or an empty string in a given field, but it's not possible to use string.IsNullOrEmpty to do it, even though many other string methods map to LINQ to SQL.
Proposed Solution
Allow string.IsNullOrEmpty in a LINQ to SQL where clause so that these two queries have the same result:

var fieldNullOrEmpty =
from item in db.SomeTable
where item.SomeField == null || item.SomeField.Equals(string.Empty)
select item;

var fieldNullOrEmpty2 =
from item in db.SomeTable
where string.IsNullOrEmpty(item.SomeField)
select item;

Other Reading:

1. DevArt

2. Dervalp.com

3. StackOverflow Post



Related Topics



Leave a reply



Submit