EF Code First:如何获取随机行 [英] EF Code First: How to get random rows

查看:45
本文介绍了EF Code First:如何获取随机行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何构建查询以检索随机行?

How can I build a query where I would retrieve random rows?

如果我用 SQL 编写它,那么我会在 newid() 上放置一个 order by 并从顶部切掉 n 行.无论如何要先在 EF 代码中执行此操作?

If I were to write it in SQL then I would put an order by on newid() and chop off n number of rows from the top. Anyway to do this in EF code first?

我尝试创建一个使用 newid() 的查询并使用 DbSet.SqlQuery() 执行它.虽然它有效,但它不是最干净的解决方案.

I have tried creating a query that uses newid() and executing it using DbSet.SqlQuery(). while it works, its not the cleanest of solutions.

此外,尝试检索所有行并按新的 guid 对它们进行排序.虽然行数比较少,但仍然不是一个好的解决方案.

Also, tried retrieve all the rows and sorting them by a new guid. Although the number of rows are fairly small, its still not a good solution.

有什么想法吗?

推荐答案

只需拨打:

something.OrderBy(r => Guid.NewGuid()).Take(5)

这篇关于EF Code First:如何获取随机行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆