EF Code First: How to get random rows

Mel picture Mel · Oct 16, 2011 · Viewed 31.5k times · Source

How can I build a query where I would retrieve random rows?

If I were to write it in SQL then I would put an order by on newid() and chop off n number of rows from the top. Anyway to do this in EF code first?

I have tried creating a query that uses newid() and executing it using DbSet.SqlQuery(). while it works, its not the cleanest of solutions.

Also, tried retrieve all the rows and sorting them by a new guid. Although the number of rows are fairly small, its still not a good solution.

Any ideas?

Answer

SLaks picture SLaks · Oct 16, 2011

Just call:

something.OrderBy(r => Guid.NewGuid()).Take(5)