NHibernate QueryOver Support For OrderBy Random

I had a need to get random records from the database, so I came up with this extension to the NHibernate QueryOver api. It is for Microsoft SQL Server, but it shouldn’t take much effort to port it to other database flavors.

public static class NHibernateExtensions
{
  public static IQueryOver<TRoot, TSubType> OrderByRandom<TRoot, TSubType>(this IQueryOver<TRoot, TSubType> query)
  {
    query.UnderlyingCriteria.AddOrder(new RandomOrder());
    return query;
  }
}

public class RandomOrder : Order
{
  public RandomOrder() : base("", true)
  {
  }

  public override SqlString ToSqlString(ICriteria criteria, ICriteriaQuery criteriaQuery)
  {
    return new SqlString("newid()");
  }
}

Leave a Reply

Your email address will not be published. Required fields are marked *