To do this with NHibernate you need to add the following class ...
public class RandomOrder : Order
{
public RandomOrder()
: base(String.Empty, true)
{ }
public override SqlString ToSqlString(ICriteria criteria, ICriteriaQuery criteriaQuery)
{
return new SqlString("NEWID()");
}
}
And the following extension method ...
public static IQueryOver<TRoot, TSubType> OrderByRandom<TRoot, TSubType>(this IQueryOver<TRoot, TSubType> query)
{
query.UnderlyingCriteria.AddOrder(new RandomOrder());
return query;
}
This will allow you to do the following ...
var test = session.QueryOver<Entity>().OrderByRandom().Take(5).ToList();
To do this with NHibernate FluentMapping and Linq to NHibernate ...
Add a new property to your class
public virtual string Random { get; set; }
Then add the flowing mapping to your ClassMap<T>
Map(o => o.Random).Formula("NEWID()");
Finally you can call it via the following
ctx.Query<T>().OrderBy(o => o.Random).Take(5).ToList();
And to do this with EF you need to add the following method to your DataContext class ...
[Function(Name = "NEWID", IsComposable = true)]
[return: Parameter(DbType = "uniqueidentifier")]
public Guid Random()
{
return Guid.NewGuid();
}
then you can call it by doing the following ...
dc.Products.OrderBy(o => dc.Random()).Take(5)
which will give you the following results ...
SELECT TOP(5) * FROM Products ORDER BY NEWID()