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

标签 c# linq entity-framework linq-to-entities

我今天在我的一个 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;

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

关于c# - 条件或对 Linq-to-entities 没有影响?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15723978/

相关文章:

c# - 在 C# 中从 ListView 中选择一个项目

c# - LINQ 实现 - 一个循环还是多个循环?

c# - 在 Unity 中顺畅地逐 block 移动播放器

c# - 如何在 C# 中以像素级操作图像

c# - 在 Visual Studio 2012 中使用 newton.jsoft (json.net) 将 c# 翻译为 vb .net 时出现翻译错误

c# - 如何在 LINQ 中组合对象属性中的列表?

c# - Hierarchyid 数据类型和 Code First

.net - 我可以在 Entity Framework 中进行模型级过滤吗?

c# - 使用动态属性搜索 LINQ 中的 Where 子句

c# - 为什么C#禁止接口(interface)成员的内部访问?