Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I select a Random Row using NHibernate's ICriteria API?

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

like image 833
Andrey Selitsky Avatar asked Apr 08 '09 12:04

Andrey Selitsky


2 Answers

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()");
    }
}
like image 96
Mauricio Scheffer Avatar answered Sep 21 '22 07:09

Mauricio Scheffer


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")

like image 37
user52212 Avatar answered Sep 24 '22 07:09

user52212