sto imparando su LINQ to SQL e tutto andava bene fino a quando qualcosa di strano è accaduto:DISTINCT() e OrderBy problema
Ho provato a fare un esempio di distinct
, quindi, utilizzando il dabatase Northwind ho scritto la seguente query:
var query =
from o in db.Orders
orderby o.CustomerID
select new
{
o.CustomerID
};
se stampo il codice SQL generato da LINQ to SQL per la query memorizzata in query
sembra che questo:
SELECT [t0].[CustomerID]
FROM [dbo].[Orders] AS [t0]
ORDER BY [t0].[CustomerID]
Quindi, come al solito, la query porta tutti gli CustomerID
per ogni Order
nella tabella Orders
ordinata alfabeticamente.
Ma! Se uso il metodo Distinct()
in questo modo:
var query = (
from o in db.Orders
orderby o.CustomerID
select new
{
o.CustomerID
}).Distinct();
La query porta i risultati attesi della clausola Distinct
, ma i CustomerID
s non sono ordinate, nonostante ho scritto orderby o.CustomerID
!
La query SQL per questa seconda query LINQ è il seguente:
SELECT DISTINCT [t0].[CustomerID]
FROM [dbo].[Orders] AS [t0]
Come possiamo vedere ** clausola ORDER BY
è mancante. Perché?
Perché la clausola ORDER BY
scompare quando utilizzo il metodo Distinct()
?
Per inciso sintassi lambda è molto più semplice per le query di questo tipo: 'var query = db.Orders.Select (o => o .CustomerId) .Distinct(); ' – asawyer