What is the best (and fastest) way to retrieve a random row using Linq to SQL when I have a condition, e.g. some field must be true?
To add to Marc Gravell's solution. If you are not working with the datacontext class itself (because you proxy it somehow e.g. to fake the datacontext for testing purposes), you cannot use the defined UDF directly: it will not be compiled to SQL because you're not using it in a subclass or partial class of your real data context class.
A workaround for this problem is to create a Randomize function in your proxy, feeding it with the query you want to be randomized:
public class DataContextProxy : IDataContext
{
private readonly DataContext _context;
public DataContextProxy(DataContext context)
{
_context = context;
}
// Snipped irrelevant code
public IOrderedQueryable Randomize(IQueryable query)
{
return query.OrderBy(x => _context.Random());
}
}
Here is how you'd use it in your code:
var query = _dc.Repository();
query = _dc.Randomize(query);
To be complete, this is how to implement this in the FAKE datacontext (which uses in memory entities):
public IOrderedQueryable Randomize(IQueryable query)
{
return query.OrderBy(x => Guid.NewGuid());
}