按随机顺序按新Guid排序

时间:2014-01-06 15:17:27

标签: sql linq entity-framework linqpad

为了从Sql查询中以随机顺序获得结果,我通常按新Guids排序。我之前已经使用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()只被调用一次。

(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]

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

我认为问题是由LinqPad直接查询数据库(而不是创建自己的EF连接)创建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(),然后您将获得所需的随机排序。

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