Picking random record from Entity Framework database without OrderBy

c# entity-framework linq

Question

I try to get random record from database:

 personToCall = db.Persons.Skip(toSkip).Take(1).First();

but I get exception which tells me:

{"The method 'Skip' is only supported for sorted input in LINQ to Entities. The method 'OrderBy' must be called before the method 'Skip'."}

Can I do it without OrderBy? Sorting data structure (O(nlogn)) to pick random element(which should be constant) doesn't look wise.

EDIT: I use Entity Framework 6.1.1.

1
6
9/14/2014 4:06:16 PM

Accepted Answer

You can have something like :

personToCall = db.Persons.OrderBy(r => Guid.NewGuid()).Skip(toSkip).Take(1).First();

You should use FirstOrDefault to be mode defensive.

Here the dark lord teaching the force to yoda! what is the world coming to!

24
9/14/2014 4:03:11 PM

Popular Answer

First you need to get the random number from 1 to max record, see this

Random rand = new Random();
int toSkip = rand.Next(1, db.Persons.Count);

db.Persons.Skip(toSkip).Take(1).First();

with order by you can use the Guid.NewGuid()

db.Persons.OrderBy(x=>x.Guid.NewGuid()).Skip(toSkip).Take(1).FirstOrDefault();


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow