用于处理可为 nullable DateTime 的 LINQ 查询中的三元运算符抛出异常

Ternary operator in LINQ queries used for handle nullable DateTime throws the exception

我有一些过滤器 class。此 class 具有可为空的日期字段。

public class Filter
{
   DateTime? date;
}

然后我有一些 LINQ 查询,它使用 nHibernate 的 IQueryable 对象。我有一个条件:

Where(x=>...
some expression
&& !Model.date.HasValue ? true : (x.fooDate.Date == Model.date.Value.Date)
&& some expresion

不幸的是它抛出了异常(即PartialEvaluationExceptionExpression)。可能它会尝试评估表达式的错误路径,而 Model.date.Value 不存在。

我该如何处理?我知道我可以做这样的事情:

if(!Model.Date.HasValue)
{
    Where(x=>...
    some expression
    //Mentioned condition is omitted
    && some expression
}
else
{
    Where(x=>...
    some expression
    && (x.fooDate.Date == Model.date.Value.Date)
    && some expresion 
}

嗯,为什么不直接写成:

Where(x=>...
    !Model.date.HasValue ? 
       true : 
       (Model.date.Value != null 
         && x.fooDate.Date == Model.date.Value.Date)

更新

更准确地看这个表达式——我不认为 Model.date.Value 在表达式的第二个分支中可以为 null。更有可能是 x.fooDate,因此第二个分支应如下所示:

(x.fooDate != null && x.fooDate.Date == Model.date.Value.Date)

我会把它分成一个或:

Where(x=>...
    (Model.date == null || x.fooDate.Date == Model.date.Value.Date)

我不确定 HasValue 是否有效,而且我没有从这里进行测试的简单方法,所以我将其更改为空值检查。

我决定通过按如下方式划分查询来省略问题:

query = Where(x=>...
some expression
&& some expresion
&& some expresion
&& some expresion);

if(Model.date.HasValue)
{
    query = query.Where(x=>...
        x.fooDate.Date == Model.date.Value.Date);
}