我有一个创建hql查询并动态附加order by子句的函数,然后执行查询。查询返回正确的结果,但它们不是按订单设置的顺序。
public List<Event> Search(string sortby)
{
string query = "from Event e and e.IsDeleted = 0 ";
if (sortby != null && sortby != "")
{
var useDesc = sortby.EndsWith("Desc");
var name = useDesc
? sortby.Remove(sortby.Length - 4, 4)
: sortby;
switch (name)
{
case "Name":
query = query + " order by e.Name ";
break;
case "DateCreated":
query = query + " order by e.CreatedOn ";
break;
default:
break;
}
query = useDesc ? query + " desc" : query + " asc";
}
var HqlQuery = session.CreateQuery(query);
IList<Event> events = HqlQuery.List<Event>().ToList();
return events;
}
为什么这会返回错误的顺序。
答案 0 :(得分:1)
如果没有映射,我可以指出两个问题
首先,此查询应为:
// the 'and' is weird
// string query = "from Event e and e.IsDeleted = 0 ";
// should be
string query = "from Event e WHERE e.IsDeleted = 0 ";
第二,HQL是关于C#属性(不是列)。所以,这里让我感到困惑的是字符串/名称不一致
// here we get from upper layers the string 'DateCreated'
case "DateCreated":
// while here we do order over the 'CreatedOn'
query = query + " order by e.CreatedOn ";
这些是提示,可以在没有更多细节的情况下看到
(我的意思是:NHibernate中的HQL一般正常工作.QuickBy子句按预期实现)