EF代码优先:如何获得随机行

我怎样才能build立一个查询,我会检索随机行?

如果我在SQL中编写它,那么我将在newid()上放置一个命令,并从顶部砍掉n个行。 无论如何要在EF代码中做到这一点?

我已经尝试创build一个使用newid()并使用DbSet.SqlQuery()执行它的查询。 虽然它的工作,它不是最干净的解决scheme。

另外,试着检索所有的行,并通过一个新的GUIDsorting。 尽pipe行数相当小,但它仍然不是一个好的解决scheme。

有任何想法吗?

2 Solutions collect form web for “EF代码优先:如何获得随机行”

只要打电话:

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

比较两个选项:


跳过(随机数行)

方法

 private T getRandomEntity<T>(IGenericRepository<T> repo) where T : EntityWithPk<Guid> { var skip = (int)(rand.NextDouble() * repo.Items.Count()); return repo.Items.OrderBy(o => o.ID).Skip(skip).Take(1).First(); } 
  • 需要2个查询

生成的SQL

 SELECT [GroupBy1].[A1] AS [C1] FROM (SELECT COUNT(1) AS [A1] FROM [dbo].[People] AS [Extent1]) AS [GroupBy1]; SELECT TOP (1) [Extent1].[ID] AS [ID], [Extent1].[Name] AS [Name], [Extent1].[Age] AS [Age], [Extent1].[FavoriteColor] AS [FavoriteColor] FROM (SELECT [Extent1].[ID] AS [ID], [Extent1].[Name] AS [Name], [Extent1].[Age] AS [Age], [Extent1].[FavoriteColor] AS [FavoriteColor], row_number() OVER (ORDER BY [Extent1].[ID] ASC) AS [row_number] FROM [dbo].[People] AS [Extent1]) AS [Extent1] WHERE [Extent1].[row_number] > 15 ORDER BY [Extent1].[ID] ASC; 

GUID

方法

 private T getRandomEntityInPlace<T>(IGenericRepository<T> repo) { return repo.Items.OrderBy(o => Guid.NewGuid()).First(); } 

生成的SQL

 SELECT TOP (1) [Project1].[ID] AS [ID], [Project1].[Name] AS [Name], [Project1].[Age] AS [Age], [Project1].[FavoriteColor] AS [FavoriteColor] FROM (SELECT NEWID() AS [C1], [Extent1].[ID] AS [ID], [Extent1].[Name] AS [Name], [Extent1].[Age] AS [Age], [Extent1].[FavoriteColor] AS [FavoriteColor] FROM [dbo].[People] AS [Extent1]) AS [Project1] ORDER BY [Project1].[C1] ASC 
  • 如何声明外键关系在MVC3中使用代码第一entity framework(4.1)?
  • entity framework数据库中的代码优先默认数据
  • types或名称空间名称“实体”不存在于名称空间“System.Data”
  • 为什么。包容很慢? 通过主键获取多个实体的最有效方法?
  • 为什么在EF 4.1中插入实体与ObjectContext相比如此之慢?
  • 如何在Entity Framework Code First中分离对象?
  • EF ICollection Vs List Vs IEnumerable Vs IQueryable
  • 代码优先与模型/数据库优先
  • EF 4.1代码优先的复合钥匙
  • ADO.NET DbContext生成器与ADO.NET Poco实体生成器(ObjectContext)
  • entity framework代码第一。 find主键