2014-01-06 212 views
4

爲了從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] 

任何想法?

+0

@PeterRing結果的隨機順序。 –

+0

http://stackoverflow.com/questions/654906/linq-to-entities-random-order –

+0

@WalterStabosz我想這樣做在數據庫上看到 http://stackoverflow.com/a/4120132/358661 –

回答

1

我相信問題是由LinqPad在創建DBContext(或者它在內部執行的任何操作)的方式直接查詢數據庫(而不是創建自己的EF連接)造成的。如果我運行此:

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(),你會得到你想要的隨機排序。

var query = 
    from x in context.MyTable 
    orderby Guid.NewGuid() 
    select new { 
     x.ID 
    }; 
+0

這絕對不是一回事。你正在返回guid,他通過guid命令並且不返回它。 –

+0

@WiktorZychla我已經更新了我的答案 –