简体   繁体   English

使用实体框架获取多条随机记录?

[英]Get MULTIPLE random records using Entity Framework?

I have checked this answered question and other articles on Stack Overflow. 我已经检查了这个已回答的问题以及有关堆栈溢出的其他文章。 I prefer the Skip method. 我更喜欢“ Skip方法。 However, they are all for single record. 但是,它们都是单个记录。 Now assume I want to take 20 random records from a table, how can I do that? 现在假设我要从一个表中获取20条随机记录,该怎么办?

I am trying two possibilities: 我正在尝试两种可能性:

  1. Generate an array of indexes and use Skip for each. 生成一个索引数组,并对每个索引使用“跳过”。 This, however, results in 20 queries (and each is ordered by Id too). 但是,这会导致20个查询(每个查询也都由ID排序)。

  2. Fetch the list of all Ids and pick randomly into an array and perform a 2nd query for detailed info all selected Ids. 获取所有ID的列表,然后随机选择一个数组,并执行第二次查询以获取所有选定ID的详细信息。

  3. Or just use OrderBy as the other post suggested. 或者只是使用OrderBy作为其他帖子建议。 I think this can be bad because the entire table is ordered? 我认为这可能是不好的,因为整个表都是有序的?

Please tell me if there is any better solution. 请告诉我是否有更好的解决方案。

Can you not use a Stored Proc to do this for you? 您不能使用Stored Proc为您执行此操作吗?

So your StoredProcs job is to return 20 records to the caller (I guess this is some Online Exam :D) 因此,您的StoredProcs工作是将20条记录返回给调用方(我想这是一些在线考试:D)

on the sql side you can use SQL Rand() to generate random numbers for all rows in your Table. 在sql端,您可以使用SQL Rand()为表中的所有行生成随机数。 Then Order them by Asc/Desc values of this Random column and Pick top 20. 然后按此Random列的Asc / Desc值对它们进行排序,并选择前20个。

Ordering the table by randomized guid will not leave any effects on the table. 通过随机guid对表进行排序不会对表产生任何影响。 The Linq solution achieves what you want to do. Linq解决方案实现了您想要做的事情。

private IEnumerable<MyClass> GetRandomItems(int n)
{
    return _dbContext.MyClass.OrderBy(x => Guid.NewGuid()).Take(n);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM