简体   繁体   English

Linq Where子句未对空字符串执行String.Contains(String)时返回我期望的结果

[英]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. 正如我期望的那样,这使我得到了我所有的MyClass DB记录。

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

This returned a 0 Count collection!! 这返回了0计数集合! 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. 这将再次返回包含所有MyClass DB记录的集合。 This is normal as i.TAG always contains "e". 这是正常现象,因为i.TAG始终包含“ e”。

Why do I get a 0 members collection with the second expression? 为什么我在第二个表达式中得到一个0成员集合? "string".Contains("") should always be true right? “ string” .Contains(“”)应该总是正确的吧?

PS: Extension.getDBService() is a call to a DBContext by the way. PS:Extension.getDBService()是对DBContext的调用。

Thx for your assistance. 谢谢您的协助。

Interestingly, the way you wrote the LINQ query generates SQL CHARINDEX(...) > 0 criteria which returns false for empty string. 有趣的是,您编写LINQ查询的方式会生成SQL CHARINDEX(...) > 0条件,该条件对于空字符串返回false。

However, if you remove (move outside the query) the ToLower().Trim() part of the SearchTag variable 但是,如果删除(移至查询之外) SearchTag变量的ToLower().Trim()部分

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. 在LINQ查询中,则生成的SQL条件是LIKE运算符,并且按预期工作。

Just another example that LINQ to Entities is not like LINQ to Objects. LINQ to Entities的另一个示例与LINQ to Objects不同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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