简体   繁体   中英

Linq Where clause not returning what I expect when performing String.Contains(String) on a null string

I scratched my head for one hour on this yesterday with no results but sweat.

string SearchTag = "";
Extension.getDBService<MyClass>().FindAll(i => <true condition>);

This returned me all my MyClass DB records as I would expect.

string SearchTag = "";
Extension.getDBService<MyClass>().FindAll(i => <true condition> && i.TAG.ToLower().Trim().Contains(SearchTag.ToLower().Trim()));

This returned a 0 Count collection!! I do not understand this.

string SearchTag = "e";
Extension.getDBService<MyClass>().FindAll(i => <true condition> && i.TAG.ToLower().Trim().Contains(SearchTag.ToLower().Trim()));

This returns a collection containing all MyClass DB records again. This is normal as i.TAG always contains "e".

Why do I get a 0 members collection with the second expression? "string".Contains("") should always be true right?

PS: Extension.getDBService() is a call to a DBContext by the way.

Thx for your assistance.

Interestingly, the way you wrote the LINQ query generates SQL CHARINDEX(...) > 0 criteria which returns false for empty string.

However, if you remove (move outside the query) the ToLower().Trim() part of the SearchTag variable

SearchTag = SearchTag.ToLower().Trim();

and use

i.TAG.ToLower().Trim().Contains(SearchTag)

inside the LINQ query, then the generated SQL criteria is LIKE operator and works as expected.

Just another example that LINQ to Entities is not like LINQ to Objects.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM