简体   繁体   English

将空值保留在nhibernate排序中

[英]Keep null values last in nhibernate sorting

I have to keep null values always last in sorting, irrespect of sorting order(asc or desc). 无论排序顺序(asc还是desc),我都必须始终将null值排在最后。

I used code something like this. 我使用了类似这样的代码。

criteria
   .AddOrder(Order.Desc(
          Projections.Cast(
                 NHibernateUtil.Decimal, 
                 Projections.Property("col1"))));

criteria
     .AddOrder(Order.Asc(
           Projections.Cast(
                 NHibernateUtil.Decimal, 
                 Projections.Property("col1"))));

i have read this link : 我已阅读此链接:

http://www.techrepublic.com/blog/datacenter/control-null-data-in-oracle-using-the-order-by-clause/121 http://www.techrepublic.com/blog/datacenter/control-null-data-in-oracle-using-the-order-by-clause/121

UPDATE 更新

In this link you can see nulls last for sorting. 在此链接中,您可以看到null进行最后排序。 how can i implement this in nhibernate in above code? 如何在上面的代码中的nhibernate中实现此功能? any help? 有什么帮助吗?

We can use standard SQL Function COALESCE and use it as a projection for ORDER BY 我们可以使用标准的SQL函数COALESCE并将其用作ORDER BY的投影

using NHibernate.Dialect.Function;
using NHibernate.Criterion;
...

// sql function definition
var sqlFunction = new SQLFunctionTemplate(NHibernateUtil.String
                                         , "COALESCE(Col1, 'zzzz')");
// create projection
var projection = Projections.SqlFunction(sqlFunction, NHibernateUtil.String);

// order by projection
criteria.AddOrder(new Order(projection, false));

And it depends on your needs how will be NULL substituted ('zzzzz' or '000' or ..) to move it at the end or at the beginning. 并且取决于您的需要,如何在结尾或开头将NULL替换('zzzzz'或'000'或..)。 So if the order is ascending projection will use high chars if descending low chars. 因此,如果顺序为升序,则投影将使用高位字符,如果降序为低位字符。 While there is some overhead, it will do that job 虽然有一些开销,但它将完成这项工作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM