简体   繁体   English

检索随机数据库记录

[英]Retrieve random DB record

What is the best way to retrieve a "X" number of random records using Entity Framework (EF5 if it's relevant). 使用实体框架(如果有的话,是EF5)检索“ X”数量的随机记录的最佳方法是什么。 The value of "X" will be set based on where this will be used. “ X”的值将根据使用位置进行设置。

Is there a method for doing this built into EF or is best to pull down a result set and then use a C# random number function to pull the records. 是否有一种内置于EF的方法,或者最好是提取结果集,然后使用C#随机数函数提取记录。 Or is there a method that I'm not thinking of? 还是我没有想到的方法?


On the off chance that it's relevant I have a table that stores images that I use for different usages (there is a FK to an image type table). 如果有相关性,我有一个表可以存储我用于不同用途的图像(图像类型表有FK)。 The images that I use in my carousel on the homepage is what I'm wanting to add some variety to...consequently how "random" it is doesn't matter to me much. 我要在首页的轮播中使用的图像是我要添加的各种颜色,因此,“随机性”对我来说并不重要。 I'm just trying to get away from the same six or so pictures always being displayed. 我只是想摆脱总是显示相同的六张左右的图片。 (Also, I'm not really interested in debating/discussing storing images in a table vs local storage.) (此外,我对辩论/讨论将图像存储在表中还是本地存储中并不真正感兴趣。)


The solution needs to be one using EF via a LINQ statement. 该解决方案必须是通过LINQ语句使用EF的解决方案。 If this isn't directly possibly I may end up doing something SIMILAR to what @cmd has recommended in the comments. 如果这不是直接可能的话,我可能最终会执行类似于@cmd在注释中建议的操作。 This would most likely be a matter of retrieving a record count...testing the PK to make sure the resulting object wasn't null and building a LIST of the X number of object's PKs to pass to front end. 这极有可能是检索记录个性化......测试PK,以确保得到的对象是不是null,建设的问题LIST对象的PK的X号传递到前端。 The carousel lazy loads the images so I don't actually need the image when I'm building the list that will be used by the carousel. 轮播懒惰加载图像,因此在构建轮播使用的列表时,我实际上并不需要该图像。

Can you just add an ORDER BY RAND() clause to your query? 您可以只在查询中添加ORDER BY RAND()子句吗?

See this related question: MySQL: Alternatives to ORDER BY RAND() 参见以下相关问题: MySQL:ORDER BY RAND()的替代方法

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

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