我有以下Linq-to-SQL语句:
return db.Photos.SingleOrDefault(p => p.PhotoID == id
&& includePending ? true : p.Live);
Run Code Online (Sandbox Code Playgroud)
对于includePending,我传递的是假的.在数据库中,"Live"适用于除2张照片以外的所有照片.
但是,不是按预期返回一张照片,而是返回数据库中的所有照片,除了2!PhotoID是主键(因此对于一个项只能是true),而布尔逻辑表示FALSE和TRUE = FALSE.那么这里发生了什么?为什么忽略p.PhotoID == id我的查询部分?
Jon*_*eet 11
我不记得完整的优先规则,但你的条件相当于:
p => (p.PhotoID == id && includePending) ? true : p.Live
Run Code Online (Sandbox Code Playgroud)
而你想要:
p => p.PhotoID == id && (includePending ? true : p.Live)
Run Code Online (Sandbox Code Playgroud)
只需使用后一种形式使其明确,甚至将其更改为不使用条件:
p => p.PhotoID == id && (includePending || p.Live)
Run Code Online (Sandbox Code Playgroud)
我认为这更简单.我建议在这样的情况下,即使优先规则对你有利,你也可以使用包围来使逻辑更清晰.
你甚至可以使用两个where子句:
.Where(p => p.PhotoID == id)
.Where(p => includePending || p.live)
Run Code Online (Sandbox Code Playgroud)
甚至是第二个条件:
var query = ...
.Where(p => p.PhotoID == id);
if (!includePending)
{
query = query.Where(p => p.live);
}
Run Code Online (Sandbox Code Playgroud)