Patrick’s Bytes

Techie for the past 30 years…

Random results from LINQ to SQL

A lot of applications would like to return random results from database. For example an web ad engine that returns random ads from its database based on certain conditions.

To do this in LINQ to SQL you need a bit of programming in T-SQL because LINQ does not have a Random operator nor you can use System.Random in LINQ statements.

Fortunately, LINQ to SQL lets programmers expose their functions and stored procs as methods. So what we can do is create a view first:

CREATE VIEW RandomView
AS
SELECT NEWID() As ID

Then after that you create a function:

CREATE FUNCTION GetNewId
(
)
RETURNS uniqueidentifier
AS
BEGIN
RETURN (SELECT ID FROM RandomView)
END

In the LINQ to SQL Designer, drag and drop the function into the designer (pic below)

image

From your LINQ query you can then write something like this

var tools =
  from tool in db.Tools
  orderby db.GetNewId()
  select tool.Name;

Many thanks to Fabrice for his post here.

http://weblogs.asp.net/fmarguerie/archive/2008/01/10/randomizing-linq-to-sql-queries.aspx

No Responses to “Random results from LINQ to SQL”

RSS feed for comments on this post. TrackBack URL

Leave a Response