为了从Sql查询中以随机顺序获取结果,我通常按新的Guid进行排序。我之前已经使用Entity- Framework完成了此操作,但是由于某种原因,它现在无法正常工作。
例如(使用Adventureworks2008r2数据库),我在LinqPad中运行以下查询:
(from t in Employees orderby Guid.NewGuid() select new {t.Person.FirstName,t.Person.LastName,t.JobTitle})
这将生成以下SQL:
SELECT [t1].[FirstName], [t1].[LastName], [t0].[JobTitle] FROM [HumanResources].[Employee] AS [t0] INNER JOIN [Person].[Person] AS [t1] ON [t1].[BusinessEntityID] = [t0].[BusinessEntityID]
那么我的orderby查询发生了什么?
我通过以下查询进一步迈出了这一步,发现Guid.NewGuid()它只被调用了一次。
Guid.NewGuid()
(from r in (from t in Employees select new {t.Person.FirstName,t.Person.LastName,t.JobTitle, g = Guid.NewGuid()}) orderby r.g select r)
这产生了以下SQL查询
-- Region Parameters DECLARE @p0 UniqueIdentifier = '68ad5016-19ca-4e31-85c3-1d45618ea8c9' -- EndRegion SELECT [t2].[FirstName], [t2].[LastName], [t2].[JobTitle] FROM ( SELECT [t1].[FirstName], [t1].[LastName], [t0].[JobTitle], @p0 AS [value] FROM [HumanResources].[Employee] AS [t0] INNER JOIN [Person].[Person] AS [t1] ON [t1].[BusinessEntityID] = [t0].[BusinessEntityID] ) AS [t2] ORDER BY [t2].[value]
知道发生了什么吗?
我相信问题是由直接查询数据库(而不是创建自己的EF连接)时LinqPad创建DBContext(或内部执行的任何操作)引起的。如果我运行此命令:
using (var context = new MyContext()) { var query = from x in context.MyTable select new { x.ID, g = Guid.NewGuid() }; }
我得到以下SQL
SELECT [Extent1].[ID] AS [ID], NEWID() AS [C1] FROM [dbo].[MyTable] AS [Extent1]
这将导致每一行的唯一GUID。您可以将Linq更改为,orderby Guid.NewGuid()然后将获得所需的随机排序。
orderby Guid.NewGuid()
var query = from x in context.MyTable orderby Guid.NewGuid() select new { x.ID };