对象引用未设置为LINQ to SQL查询中的实例
本文关键字:查询 实例 SQL to 设置 LINQ 对象引用 | 更新日期: 2023-09-27 18:00:58
我的LINQ to SQL查询有问题,从服务器返回的数据可能为null,所以我在查询中设置了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;
如果搜索词"Location"为null,那么我不想按位置进行筛选,但如果它不为null,则我必须检查行中的值是否为null,因为有些条目的位置为null。
在我添加比较行之前,代码运行良好。为了到达比较行,Query.Location和b.Location都不能为null,因此代码不应该失败。
你知道可能是什么问题吗?
谢谢。
编辑
如果我从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;
我不想确切地说这里出了什么问题,但我认为您实际上可以通过将代码拆分为两个不同的查询来简化代码:
public void Search(SearchTerms Query)
{
var queryWithLocation = db.branches.Where(b =>
Query.Location.Equals(b.Location, StringComparison.OrdinalIgnoreCase);
var query = Query.Location != null ? queryWithLocation : db.branches;
}
我已经改变了执行Equals
的方式——这是我更喜欢执行不区分大小写的搜索的方式;您必须看看它是否适用于LINQ to SQL。
试试这个;
public void Search(SearchTerms Query)
{
var a = from b in db.branches
where (b.Location != null) ?
(
(Query.Location == null) ?
true
:
//The following line causes the exception to be thrown
Query.Location.ToLower() == b.Location.ToLower()
)
:
(
(Query.Location == null) ?
true
:
false
)
select b
}
我认为object
可能导致了NullReference
from b in db.branches
let location = b.Location
where location != null ?
b.Location.Equals(b.Location, Query.Location ?? b.Location, StringComparison.OrdinalIgnoreCase) : // if Query.Location is null then select all
false // to select nothing in this case
select b;