gpt4 book ai didi

c# - Linq-to-SQL 的三元运算符导致问题?

转载 作者:行者123 更新时间:2023-11-30 19:12:43 24 4
gpt4 key购买 nike

我有以下 Linq-to-SQL 语句:

return db.Photos.SingleOrDefault(p => p.PhotoID == id
&& includePending ? true : p.Live);

对于 includePending,我传递的是 false。在数据库中,除了 2 张照片外,所有照片都为“实时”。

然而,它并没有像预期的那样返回一张照片,而是返回了数据库中除了 2 张照片之外的所有照片! PhotoID 是一个主键(因此只能对一项为真)并且 bool 逻辑表明 FALSE AND TRUE = FALSE。那么这是怎么回事?为什么它会忽略我查询的 p.PhotoID == id 部分?

最佳答案

我不记得 full precedence rules心,但你的条件相当于:

p => (p.PhotoID == id && includePending) ? true : p.Live

而你想要:

p => p.PhotoID == id && (includePending ? true : p.Live)

只需使用后一种形式使其显式化,甚至将其更改为不使用条件:

p => p.PhotoID == id && (includePending || p.Live)

我认为这更简单。我建议在这种情况下,即使优先规则对您有利,您也可以使用括号使逻辑更清晰。

您甚至可以使用两个 where 子句:

.Where(p => p.PhotoID == id)
.Where(p => includePending || p.live)

甚至条件化第二个:

var query = ...
.Where(p => p.PhotoID == id);

if (!includePending)
{
query = query.Where(p => p.live);
}

关于c# - Linq-to-SQL 的三元运算符导致问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6197634/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com