views:

111

answers:

1

I need to retrieve random rows from SQL Server database. I am looking for a way to achieve this using LINQ query. Is it possible?

SQL Query: SELECT [Id] FROM [MyTable] ORDER BY NEWID()

What is the equivalent LINQ query for the above SQL?

Thanks in advance.

+1  A: 

Make a partial for your data context class and put in the following method:

partial class MyDataContext {
    [Function(Name = "NEWID", IsComposable = true)]
    public Guid Random()
    {
     return Guid.NewGuid();
    }
}

Now you can compose this into your query and it'll get translated into calls to the sql newid() function like so:

from x in dc.MyEntities orderby dc.Random() select x.Id
Craig Quillen