Note that there are some explanatory texts on larger screens.

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

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload