【发布时间】:2011-09-25 20:53:18
【问题描述】:
我在使用 LINQ to SQL 查询时遇到问题,从服务器返回的数据可能为空,因此我在查询中设置了 if 语句,但查询仍然抛出异常。
这是查询代码的简化版
var a = from b in db.branches
where (b.Location != null) ?
(
(Query.Location == null) ?
true :
//The following line causes the exception to be thrown
object.Equals(Query.Location.ToLower() , b.Location.ToLower())
) :
(
(Query.Location == null) ?
true :
false
)
select b;
如果搜索词“位置”为空,那么我不想按位置过滤,但如果它不为空,那么我必须检查行中的值是否为空,因为某些条目有一个空位置。
在我添加比较行之前,代码运行良好。为了到达比较行,Query.Location 和 b.Location 都不能为空,因此代码不应该失败。
知道可能是什么问题吗?
谢谢。
编辑
如果我从 object.equals 调用中删除 .toLower() ,则查询运行正常,无论查询处于何种情况,它也都能正常工作。
var a = from b in db.branches
where (b.Location != null) ?
(
(Query.Location == null) ?
true :
//The following line causes the exception to be thrown
object.Equals(Query.Location , b.Location)
) :
(
(Query.Location == null) ?
true :
false
)
select b;
【问题讨论】:
-
如果
b.Location为null 而Query.Location不是,是否需要不选择行? -
如果
b.Location为空且Query.Location为空,是否需要选择所有行? -
如果 b.location 为 null 并且 query.location 不是,则不返回它 如果 b.location 为 null 并且 query.location 为 null 然后返回
标签: c# .net linq-to-sql exception-handling nullreferenceexception