0

I need to select from a MySQL database using Entity Framework Core (with Pomelo provider), 10 random records where their IDs are between 1 to 600. Is it possible?

I tried dbContext.MyTable.OrderBy(r => Guid.NewGuid()).Take(10); as stated in other threads, but apparently it won't work with MySQL.

Any ideas?

1 Answers1

1
    var ids = new List<int>();
var r = new Random();
for (int i = 0; i < 10; i++)
{
    ids.Add(r.Next(1,600));
}
dbContext.MyTable.Where(z => ids.Contains(z.Id)).OrderBy(x => x.Id);

There is the usual caveat that the Random class, according to Microsoft Docs, "Represents a pseudo-random number generator, which is an algorithm that produces a sequence of numbers that meet certain statistical requirements for randomness."

MarcG
  • 322
  • 1
  • 7
  • 1
    Thank you very much @Marc, it worked that way! The only thing that didn't was the ".Dump()" part...returned an error "int does not contain a definition for 'Dump' and no accessible extension method 'Dump' accepting a first argument of type 'int' could be found (are you missing a using directive or an assembly reference?). I'm still learning .net so I have no idea what this error means. – Fernando Pereira Aug 26 '21 at 19:06
  • yes... I'm sorry. I'm using Linqpad. Dump() is a Linqpad expression. I'd advise it (not linked to it all, just an enthusiastic user). There is a free version, but it's worth the every dollar if you can afford it. – MarcG Aug 26 '21 at 19:24