6

Can I select a random row using NHibernate's ICriteria API?

George Stocker
  • 57,289
  • 29
  • 176
  • 237
Andrey Selitsky
  • 2,584
  • 3
  • 28
  • 42

2 Answers2

14

Just as cundh2o said, it's DBMS-specific. But you can subclass the Order class and define your own custom ordering. For example, for SQL Server:

public class RandomOrder: Order {
    public RandomOrder() : base("", true) {}
    public override SqlString ToSqlString(ICriteria criteria, ICriteriaQuery criteriaQuery) {
        return new SqlString("newid()");
    }
}
Mauricio Scheffer
  • 98,863
  • 23
  • 192
  • 275
  • 2.1.2 compatible: public override SqlString ToSqlString(ICriteria criteria, ICriteriaQuery criteriaQuery) { return new SqlString("newid()"); } – mxmissile Sep 17 '10 at 21:14
  • 1
    Use of Newid like this leads to terrible performance on medium-size to large tables though. – UpTheCreek May 02 '11 at 09:27
1

If you are not limited to using ICriteria, I might recommend using HQL instead for selecting a random row, since it may provide more flexibility to use the Random function supplied by your db provider.


IQuery q = NHibernateSession.CreateQuery("your hql statement here")

user52212
  • 603
  • 3
  • 8
  • 18