首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >NHibernate QueryOver NullReferenceException

NHibernate QueryOver NullReferenceException
EN

Stack Overflow用户
提问于 2015-03-05 14:40:16
回答 2查看 1.3K关注 0票数 2

下面是QueryOver,它在NullReferenceException为null时抛出newExam.ActiveTo (ActiveTo类型是DateTime?)

代码语言:javascript
复制
Exam examAlias = null;
examsInSameTime = session.QueryOver(() => examAlias)
                            .Where(() => examAlias.ActiveTo == null && newExam.ActiveTo == null)
                            .Future<Exam>();

当我重写对这个HQL的查询时,一切都很好。

代码语言:javascript
复制
var query = "from Exam exam where exam.ActiveTo is null and :newExamActiveTo is null)";
examsInSameTime = session.CreateQuery(query)                
            .SetParameter("newExamActiveTo", newExam.ActiveTo).List<Exam>();

为什么QueryOver抛出异常而HQL不抛出异常?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-03-05 15:46:18

我想说,这里的解决方案应该是惊人的简单和优雅(但前提是我正确地理解了您的问题)。

重点是-检查C#中的params,不要将其发送到DB端:

代码语言:javascript
复制
Exam examAlias = null;
var query = session.QueryOver(() => examAlias);

//here we will check what needed
if(newExam.ActiveTo == null)
{
    query.Where(() => examAlias.ActiveTo == null)
}

// we can repeat that many times and build WHERE clause as required
...

// finally the query
examsInSameTime = query.Future<Exam>();

所以,这里的诀窍是:

  • 检查应用程序端的搜索参数。
  • 如果需要,将它们转换为SQL语句。
  • 只在DB端发送所需的限制
票数 1
EN

Stack Overflow用户

发布于 2015-03-05 14:48:27

正如Radim所写的,您在QueryOver中使用了一个参数。问题是,在执行查询时,newExam可能是null

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28880471

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档