1

我今天在我的一个 Linq-To-Entitites 查询中偶然发现了一个 null ref 异常,并想知道这怎么可能。似乎用作 OR 门的条件 OR 在 Linq-To-Entities 中没有效果。我的查询的一个简化示例是这样的:

from a in db.Articles
where a.Author == "John Doe"
&& (tag == null || a.Tags.Any(t => t.TagName == tag.TagName))
select a;

现在,当 tag 为 NULL 时,仍然会执行 where 查询的右侧,并且 tag.TagName 上会发生 NULL 引用异常。也许这是因为 Linq-To-Entities 总是将完整的语句翻译成 SQL?

无论如何......如何解决这个问题?

非常感谢 :)

4

2 回答 2

3
var query = db.Articles.Where(x => x.Author == "John Doe");
query = tag == null
    ? query
    : query.Where(x => x.TagName == tag.TagName);

或者:

var query = from a in db.Articles
            where a.Author == "John Doe"
            select a;

    query = tag == null
        ? query
        : from a in query
            where a.Tags.Any(t => t.TagName == tag.TagName)
            select a;

就个人而言,我发现第一个更清洁

于 2013-03-31T13:11:07.780 回答
1

Think about sql. Linq converts your code as a whole into sql query passing 'outside' objects as parameters and evaluating them. That's why it fails on evaluation of your null object.

It's a good practice to construct a linq query bit by bit based on conditions to reduce number of unnecessary code in resulted query, so it's better to split your query:

var query = db.Articles.Where(x => x.Author == "John Doe");
if( tag != null)
  query = query.Where(x => x.TagName == tag.TagName);

Because your query will be evaluated and executed on selection you are welcome to add more conditions without worrying about multiple requests.

于 2013-03-31T13:28:45.083 回答