Is there a way to return a random row from a table using LINQToSQL?
You can get LinqToSQL to generate SQL which uses the SQL Server NEWID() function. Here is my implementation:
namespace Data // change to whatever the namespace of your DataContext is, or remove
{
///
/// Add RANDOM() extension to the Data context...
///
partial class DefaultDataContext // change to the name of your DataContext
{
[System.Data.Linq.Mapping.Function(Name = "NEWID", IsComposable = true)]
public Guid Random()
{
// this code is not actually executed, it simply provides a way to access
// T-SQL "NEWID()" function from Linq to SQL
throw new NotImplementedException();
}
}
}
Example of usage, to pull a random product from the database:
var product = (from p in db.Products // our DataContext instance is called db here
orderby db.Random()
select p).FirstOrDefault()