简体   繁体   English

查询实体框架中的第n行

[英]Querying nth row in Entity Framework

I want to query a random row from a table per Entity Framework. 我想从每个实体框架的表中查询一个随机行。

The best solution I can think of in the moment is getting the total count from the table, then making per C# a function to get a random number in the range of the count and then query this random row number. 我能想到的最好的解决方案是从表中获取总计数,然后根据C#计算得到计数范围内的随机数,然后查询该随机行数。

My problem is that I can't figure out how to directly query a certain row number per Entity Framework. 我的问题是我无法弄清楚如何直接查询每个实体框架的某个行号。 I want to prevent that I need to query the whole table and then select the row number from there. 我想防止我需要查询整个表,然后从那里选择行号。

Or do I have here a general misunderstanding and there is a much simpler way? 或者我在这里有一个普遍的误解,有一个更简单的方法?

// DO NOT USE THIS FOR MORE THEN 100 ROWS
var randomRecord = foos.OrderBy( x=> SqlFunctions.Rand() ).FirstOrDefault();

But this method is less efficient then, 但是这种方法效率较低,

// USE THIS FOR MORE THEN 100 ROWS
var random = Math.Random(foos.Count());

var randomRecord = foos.OrderBy( x=> x.id ).Skip( random ).FirstOrDefault();

For database, querying count is much less overhead then actually performing SORT over RANDOM for thousands of records. 对于数据库,查询计数比实际对数千条记录执行SORT over RANDOM要少得多。 As RANDOM is certainly not indexed, so it will take very long to sort. 由于RANDOM肯定没有编入索引,因此排序需要很长时间。 So avoid using first method, use 2nd method that is the best. 所以避免使用第一种方法,使用最好的第二种方法。

This will get you the (x+1)th row. 这将获得第(x + 1)行。 If x is 0 based, then if x==0 then it will get the 1st row. 如果x基于0,那么如果x == 0则它将获得第1行。

Take(n) will dictate the query to take n rows. Take(n)将指示查询采用n行。 Skip(n) will dictate the query to skip the first n rows. Skip(n)将指示查询跳过前n行。

Thanks to AkashKava it is clear that in EF you have to use OrderBy before applying Skip. 感谢AkashKava ,很明显在EF中你必须在应用Skip之前使用OrderBy。

Since we don't care of a particular order then we can sorted like the following. 由于我们不关心特定订单,因此我们可以按如下方式进行排序。

Table.OrderBy(x=>x.id).Skip(1).Take(1)

or as also pointed out by AkashKava you could use FirstOrDeafault() 或者如AkashKava所指出的AkashKava你可以使用FirstOrDeafault()

Table.OrderBy(x=>x.id).Skip(1).FirstOrDeafault()

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

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