A A
RSS

Select Random Records Using Nhibernate

Wed, Dec 16, 2009

Programming

Selecting 5 random rows in SQL is easy

select top 5 * from users order by newid()

Nhibernate is a different story.  I am new to NHibernate and I both love and hate it.  I hate the steep learning curve and the unobvious ways of doing things.  Anyway, here is how to select 5 random records using nhibernate.

First class a new order class to perform random ordering:

public class RandomOrder : Order
{
    public RandomOrder() : base("", true) { }
    public override SqlString ToSqlString(ICriteria criteria, ICriteriaQuery criteriaQuery)
    {
        return new SqlString("newid()");
    }
}

Then use the new class in your query:

IList<User> users = session
    .CreateCriteria(typeof(User))
    .AddOrder(new RandomOrder())
    .SetMaxResults(5)
    .List<User>();

Done…

Tags: , , ,

  • The difficult part is that i also need to get 5 random records from ... the @Tbl_Organisations table in to 5 ranges and select a random
  • NHibernate is a port of the popular Java O/R mapper Hibernate to .NET. Version 1.0 mirrored the feature set of Hibernate 2.1, as well as a number of features from Hibernate 3.
  • Sure, I had put a link to http://www.mssqltips.com/tip.asp?tip=1308 in the last comment but it got stripped away...
  • I read through it and it says that it doesn't work with a small number of
    rows. I need only 5 rows... I guess I would have to do something like

    SELECT TOP 5 * FROM MyTable TABLESAMPLE (100 ROWS)

    The question is how do I do it in nhibernate. Is the only way to do this is
    to use a SQL Query?
  • Don't use order by newid() because you'll be having performance issues as the table grows (probably there will be a full table scan). Use TABLESAMPLE instead.

    see this tip.
  • Can you give us an example or a link to an example? I have never heard of
    tablesample :)
blog comments powered by Disqus
Advertise Here
The Most Intelligent Add-In To Visual Studio Happy fan of

What I'm Doing...

Yonkly Open Source

Sign up for my newsletter




* = required field

powered by MailChimp!

megree Widget

Apparently, I am connected to Obama. Check this out...
My path to Obama

Cyber Identity