问题描述
为了从Sql查询中获得随机顺序的结果,我通常按新的Guid排序。我以前用Entity-Framework做了这件事,但是由于某种原因,我们现在没有工作。
In order to get results in a random order from a Sql query I generally sort by new Guids. I have done this before with Entity-Framework, however for some reason its not working now.
例如(使用adventureworks2008r2数据库)我在LinqPad中运行以下查询:
For example (using the adventureworks2008r2 database) i run the following query in 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]
那么发生在我的订单查询发生了什么?
So what happend to my orderby query?
我进一步跟进了以下查询,发现 Guid.NewGuid()
只被调用一次。
I took this one step further with the following query to find that Guid.NewGuid()
is only being called once.
(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)
此ge调整以下SQL查询
This generated the following SQL query
-- 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]
任何想法会发生什么?
Any idea whats going on?
推荐答案
我相信问题是由LinqPad在查询数据库时创建DBContext(或其内部的任何内容)直接(而不是创建你自己的EF连接)。如果我运行这个:
I believe the problem is caused by way LinqPad is creating the DBContext (or whatever it does internally) when you query a database directly (as opposed to creating your own EF connection). If I run this:
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.NewGuid()将Linq更改为,您将获得所需的随机排序。
Which results in a unique guid for each row. You can alter the Linq to orderby Guid.NewGuid()
and you'll get the random sorting that you want.
var query =
from x in context.MyTable
orderby Guid.NewGuid()
select new {
x.ID
};
这篇关于按新指标排序随机排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!