Get a random row with LINQtoSQL

后端 未结 6 1682
忘掉有多难
忘掉有多难 2021-01-20 04:39

Is there a way to return a random row from a table using LINQToSQL?

6条回答
  •  情深已故
    2021-01-20 05:31

    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()
    

提交回复
热议问题