爲了從Sql查詢中隨機地得到結果,我通常按新的Guid排序。我之前使用Entity-Framework完成了此操作,但由於某種原因,它現在不能工作。按隨機順序的新Guid排序
例如(使用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]
所以發生了什麼我的排序依據查詢?
我採取了這一步與以下查詢進一步發現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]
任何想法?
@PeterRing結果的隨機順序。 –
http://stackoverflow.com/questions/654906/linq-to-entities-random-order –
@WalterStabosz我想這樣做在數據庫上看到 http://stackoverflow.com/a/4120132/358661 –