问题
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.
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})
This generates the following 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?
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)
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?
回答1:
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()
};
}
I get the following SQL
SELECT
[Extent1].[ID] AS [ID],
NEWID() AS [C1]
FROM [dbo].[MyTable] AS [Extent1]
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
};
来源:https://stackoverflow.com/questions/20953067/sort-by-new-guid-for-random-order