0

I am about to get 6 random rows using EF Core (v5.0.4).

Here are columns in my table:

int id(primary key,auto increase)
varchar title

Most of the tutorials (like Picking random record from Entity Framework database without OrderBy) suggest using OrderBy(r => Guid.NewGuid())

Here is my code:

Context.topics.Where(//some logic).OrderBy(X => Guid.NewGuid()).Take(6);

However, in my project, this always returns the same rows without random results.

What's wrong with it? Thank you.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Melon NG
  • 2,568
  • 6
  • 27
  • 52
  • For me, this code worked well.You can check the data of the query again.Or you can provide other more details. – Yinqiu Mar 17 '21 at 05:25
  • this should work, the generated query is like appended with `ORDER BY NEWID()`. So this means your sql provider does not support it. What I tested is for Sql Server. What provider do you use? If it's not an issue of the provider, you surely tested it wrong and ended up with a wrong assumption. – King King Mar 17 '21 at 05:27
  • What I am using is Pomelo.EntityFrameworkCore.MySql 5.0.0-alpha.2 for asp.net core 5@KingKing – Melon NG Mar 17 '21 at 05:30
  • @KingKing I tried another way by Context.topics.Where(//some logic).ToList() then orderby GUID and it doesn't work also. – Melon NG Mar 17 '21 at 05:31
  • if it does not even work for linq-to-object (orderby after `ToList()`). Then there must be something special to your data making you think that the order is not randomly changed. I doubt that you may look at some columns which have duplicate data. That causes wrong assumption. – King King Mar 17 '21 at 05:35
  • @KingKing Yes! There are so many duplicate data but with not the same id. However, how can I solve this? It seems it is needless for me to select a new one. – Melon NG Mar 17 '21 at 09:06
  • @KingKing Now I have to do it like this:Context.Topics.Where(//some logic).Select(_ => new Models.RandomTopic() { id = _.id, TopicTitle = _.title }).ToList().OrderBy(_ => Guid.NewGuid()).Take(6).ToArray() . It won't work without the ToList() and I don't know why. – Melon NG Mar 17 '21 at 10:11
  • @KingKing It seems it is because of this problem:https://stackoverflow.com/questions/20714933/random-order-with-entity-framework-and-mysql – Melon NG Mar 17 '21 at 10:20

0 Answers0