我正在尝试这样的查询......
query.Where(x => !string.IsNullOrEmpty(x.PropertyName));
Run Code Online (Sandbox Code Playgroud)
但它失败了......
所以现在我已经实现了以下功能......
query.Where(x => (x.PropertyName ?? string.Empty) != string.Empty);
Run Code Online (Sandbox Code Playgroud)
有没有更好的(更本地?)方式LINQ处理这个?
编辑
道歉!没有包含提供程序......这是使用LINQ to SQL
RSo*_*erg 43
http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=367077
问题陈述
可以编写LINQ to SQL来获取给定字段中具有null或空字符串的所有行,但是不可能使用string.IsNullOrEmpty来执行此操作,即使许多其他字符串方法映射到LINQ to SQL .建议的解决方案在LINQ to SQL where子句中允许string.IsNullOrEmpty,以便这两个查询具有相同的结果:
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;
Run Code Online (Sandbox Code Playgroud)
其他阅读:
1. DevArt
2. Dervalp.com
3. StackOverflow的帖子
Bri*_*sio 15
这在Linq2bjects上不会失败,但是对于Linq2SQL来说它会失败,所以我假设你在谈论SQL提供程序或类似的东西.
原因与SQL提供程序处理lambda表达式的方式有关.它不是一个函数Func<P,T>
,而是一个表达式Expression<Func<P,T>>
.它接受表达式树并将其转换为实际的SQL语句,然后将其发送到服务器.
翻译器知道如何处理基本操作符,但它不知道如何处理对象上的方法.它不知道IsNullOrEmpty(x)
翻译成return x == null || x == string.empty
.必须明确地完成对SQL的转换.