Bia Securities

NHibernate QueryOver Support For OrderBy Random

by on Mar.24, 2011, under NHibernate

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

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!