I'm building an asp.net core webapp, and now I need to collect a random row from the database (sql) for posting in one of the views. Would very much appreciate any help I can get in doing and understanding this. Code, explanations, links to postings, enything is useful.
I don't fully understand how EF-asp.net core works, so that's what really makes it hard in searching for posts that are related to my problem.
Thank you in advance.
/Peter
Since you are using EF, I'll provide you with a LINQ-solution.
int total = context.YourEntities.Count();
Random r = new Random();
int offset = r.Next(0, total);
var result = context.YourEntities.Skip(offset).FirstOrDefault();
All this code does is get the total number of records, and generate a random number between [0, total). Note the boundary types: inclusive from the lower-end, exclusive from the upper-end.
You use this random number as an "offset", that is, how many records to skip ( .Skip(offset)
), and then retrieve the very first element of the remaining part of the sequence. If there are no records at all, FirstOrDefault
returns null
.
在 EF (EF Core) 中,您可以通过这种方式简单地使用 LINQ 语法(OrderBy 方法):
context.MyEntities.OrderBy(r => Guid.NewGuid()).Take(10);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.