Selecting a random record from Entity Framework database without OrderBy

I am trying to get a random entry from the database:

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

      

but I am getting an exception that 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 a data structure (O (nlogn)) to select a random item (which should be constant) doesn't seem wise.

EDIT: I am using Entity Framework 6.1.1.

+3


source to share


4 answers


You might have something like:

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

      



You must use FirstOrDefault

to protect the regime.

Here the dark lord teaches the power of yoda! where the world is heading!

+17


source


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

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

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

      



with ordering you can use Guid.NewGuid ()

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

      

+5


source


There is no way to do this without an ordering clause.

personToCall = db.Persons.OrderBy (r => Random.Next ()). First ();

This can be slow depending on the size of your faces table, so if you want to do it quickly, you need to add a column to Person, or join it to the Person random numbers and keys dictionary, then order. But this is rarely a smart decision.

Better to ask a higher level question about the overall task.

+3


source


To avoid OrderBy, dump to the list and randomize against the index:

V. B.

With New List(Of Persons)
    .AddRange(db.Persons)
    PersonToCall = .Item(New Random().Next(0, .Count - 1))
End With

      

FROM#

var people = new List<Persons>();
people.AddRange(db.Persons);
personToCall  = people.Item(new Random().Next(0, people.Count - 1));

      

-1


source







All Articles