如何建立查询以检索随机行?
如果我要用SQL编写它,那么我将对newid()进行排序,并从顶部砍掉n行。无论如何要先在EF代码中执行此操作?
我尝试创建使用newid()的查询并使用DbSet.SqlQuery()执行它。虽然有效,但并不是最干净的解决方案。
另外,尝试检索所有行并按新的GUID对它们进行排序。尽管行数很小,但是它仍然不是一个好的解决方案。
有任何想法吗?
如何建立查询以检索随机行?
如果我要用SQL编写它,那么我将对newid()进行排序,并从顶部砍掉n行。无论如何要先在EF代码中执行此操作?
我尝试创建使用newid()的查询并使用DbSet.SqlQuery()执行它。虽然有效,但并不是最干净的解决方案。
另外,尝试检索所有行并按新的GUID对它们进行排序。尽管行数很小,但是它仍然不是一个好的解决方案。
有任何想法吗?
Answers:
只需致电:
something.OrderBy(r => Guid.NewGuid()).Take(5)
Guid.NewGuid()
(意味着,LinqToSql或将其变成任何东西,NEWID()
但没有人为Oracle编程相同的东西)。
比较两个选项:
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();
}
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;
private T getRandomEntityInPlace<T>(IGenericRepository<T> repo) {
return repo.Items.OrderBy(o => Guid.NewGuid()).First();
}
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
OrderBy(o => o.ID).Skip(skip).Take(5)
这并不是真正随机的,这可能会成为性能瓶颈。
.First()
”。我正在与其他一些我不再看到的答案进行比较,因此您的观点得到了双重验证。但是NewGuid
解决方案不会出现您描述的问题。