Linq-Sql IQueryable和链接 OR 运算
我正在尝试模拟:
WHERE x.IsActive = true OR x.Id = 5
以下导致使用“AND”...如何使用 IQueryable (qry) 和我的可空 int 模拟“OR”条件,考虑到可能涉及其他过滤(如此处的 IsActive 过滤器)?
if (onlyActiveItems) //bool
{
qry = qry.Where(x => x.IsActive == true);
}
if (whenSpecifiedMustIncludeRecordWithThisId.HasValue) //int?
{
qry = qry.Where(x => x.Id == whenSpecifiedMustIncludeRecordWithThisId.Value);
}
我考虑过联合,但似乎这个问题的答案应该简单得多。
这是一种解决方案,可以解决我在尝试组合所有答案时遇到的“可为空对象必须有一个值”的问题。否则,是什么导致可为 null 的值在为 null 时被求值?
if (whenSpecifiedMustIncludeRecordWithThisId.HasValue)
{
qry = qry.Where(x => (!onlyActiveItems || (onlyActiveItems && x.IsActive)) || x.Id == whenSpecifiedMustIncludeRecordWithThisId.Value);
}
else
{
qry = qry.Where(x => (!onlyActiveItems || (onlyActiveItems && x.IsActive)));
}
在某些情况下,使用 nullable 的 .Value 属性似乎也会产生影响,正如我在此处的另一个问题Linq to SQL Int16 在 SQL 命令中转换为 Int32
I'm trying to simulate:
WHERE x.IsActive = true OR x.Id = 5
The following causes 'AND' to be used... how do I simulate an 'OR' condition with IQueryable (qry) and my nullable int, given that other filtering might be involved as with the IsActive filter here?
if (onlyActiveItems) //bool
{
qry = qry.Where(x => x.IsActive == true);
}
if (whenSpecifiedMustIncludeRecordWithThisId.HasValue) //int?
{
qry = qry.Where(x => x.Id == whenSpecifiedMustIncludeRecordWithThisId.Value);
}
I have considered union but its seems the answer to this should be much simpler.
This is one solution which gets around the problem I get with "Nullable object must have a value" when trying the combined all in one answer. What causes the nullable to be evaluated when it is null otherwise?
if (whenSpecifiedMustIncludeRecordWithThisId.HasValue)
{
qry = qry.Where(x => (!onlyActiveItems || (onlyActiveItems && x.IsActive)) || x.Id == whenSpecifiedMustIncludeRecordWithThisId.Value);
}
else
{
qry = qry.Where(x => (!onlyActiveItems || (onlyActiveItems && x.IsActive)));
}
It seems also in some cases the use of the nullable's .Value property makes a difference as seen in another question of mine here Linq to SQL Int16 Gets Converted as Int32 In SQL Command
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
试试这个:
请注意,我们正在比较一个
int?
和一个int
,而不是两个int
。我在这里假设查询的目的是过滤掉是否满足某些条件。
onlyActiveItems
为 true,则验证 IsActive 字段是否为 truewhenSpecifiedMustIncludeRecordWithThisId.HasValue
为 true,则验证该值是否与 Id 字段匹配Try this:
Note that we're comparing an
int?
to anint
, not twoint
s.I am assuming here that the point of the query is to filter out if certain conditions are met.
onlyActiveItems
is true, it verifies whether the IsActive field is truewhenSpecifiedMustIncludeRecordWithThisId.HasValue
is true it verifies whether the value matches the Id field当使用“int?”时我通常使用 object.Equals(i1, i2) 来比较它们,例如
这可以避免所有可为空的问题。
When working with "int?" I usually compare them using object.Equals(i1, i2), for example
This avoids all nullable issues.