Web Technologist
Archive for April, 2010
Random Row – Linq to SQL
Apr 4th
You can retrieve a random data record from an SQL database through LINQ using a User Defined Function. We can implement the above in a partial class for the target context.
partial class MyTargetContext {
[Function(Name="NEWID", IsComposable=true)]
public Guid Random()
{
throw new NotImplementedException();
}
}
In the above example which returns a uniqe identifier (GUID), we are mapping the Random method to the NEWID SQL function. The IsComposable boolean property of the Function Attribute, defines if the method is mapped to a function (true) or to a Stored Procedure (false). Also note that since this method is mapped, the C# code is not executed.
We can call the above implementation as …
var posts = (from post in dbContext.Posts
where post.IsActive && post.Category.Equals('Linq')
order by dbContext.Random()
select post).FirstOrDefault();
Although there are better alternative in terms of performance, this approach is much easier and should work fine for small / mid-size tables.

