Skip to main content
 首页 » 编程设计

c#之条件或对 Linq-to-entities 没有影响

2024年02月13日13exmyth

我今天在我的一个 Linq-To-Entitites 查询中偶然发现了一个空引用异常,我想知道这怎么可能。用作 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?

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

非常感谢:)

请您参考如下方法:

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; 

就我个人而言,我觉得第一个更干净