gpt4 book ai didi

c# - NHibernate QueryOver NullReferenceException

转载 作者:太空宇宙 更新时间:2023-11-03 13:10:38 25 4
gpt4 key购买 nike

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

Exam examAlias = null;
examsInSameTime = session.QueryOver(() => examAlias)
.Where(() => examAlias.ActiveTo == null && newExam.ActiveTo == null)
.Future<Exam>();

当我将查询重写到此 HQL 时,一切正常

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 不会?

最佳答案

我想说,这里的解决方案应该出奇地简单和优雅(但前提是我确实正确阅读了您的问题)

关键是 - 在 C# 中检查你的参数,不要将它发送到数据库端:

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 WHERE语句
  • 仅在数据库端发送需要的限制

关于c# - NHibernate QueryOver NullReferenceException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28880471/

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