Search code examples
c#entity-frameworkentity-framework-4.1ef-code-first

EF Code First: How to get random rows


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?


Solution

  • Just call:

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