I raised a related question about:
'Invalid column name [ColumnName]' on a nested linq query
I'm trying to get the top row of a group as asked here:
Linq - Top value from each group
However, I approached it different to the accepted answer using Max. I did it this way:
ATable
.GroupBy (t => t.ID)
.Select ( t => t.OrderByDescending(x=>x.Timestamp).FirstOrDefault().Timestamp)
This results in the error SqlException: Invalid column name 'ID'
Now when I use the Max function:
ATable
.GroupBy (t => t.ID)
.Select ( t => t.Max(x=>x.Timestamp))
It returns the list of times that I wanted.
My understanding is that they are different but equivalent calls. Why am I getting the sql error on the first call?
Update
The sql query generated for the first query looks like this:
SELECT (
SELECT [t3].[Timestamp]
FROM (
SELECT TOP 1 [t2].[Timestamp]
FROM [ATable] AS [t2]
WHERE (([t1].[ID] IS NULL) AND ([t2].[ID] IS NULL)) OR (([t1].[ID] IS NOT NULL) AND ([t2].[ID] IS NOT NULL) AND ([t1].[ID] = [t2].[ID]))
ORDER BY [t2].[Timestamp] DESC
) AS [t3]
) AS [value]
FROM (
SELECT [t0].[ID]
FROM [ATable] AS [t0]
GROUP BY [t0].[ID]
) AS [t1]
I managed to reduce it down but keeping the same error:
SELECT (
SELECT [t3].[Timestamp]
FROM (
SELECT TOP 1 [Timestamp]
FROM [ATable]
WHERE [t1].[ID] = [ID]
) AS [t3]
) AS [value]
FROM (
SELECT [ID]
FROM [ATable]
GROUP BY [ID]
) AS [t1]
Update2
Some answers have said that these queries are logically different, however, if you do something like this on the northwind table, it will produce the same result:
OrderDetails
.GroupBy(x=>x.ProductID)
.Select(x=>x.OrderByDescending(y=>y.UnitPrice).FirstOrDefault().UnitPrice).Dump();
OrderDetails
.GroupBy(x=>x.ProductID)
.Select(x=>x.Max(y=>y.UnitPrice)).Dump();
So I cannot accept any of the 3 answers that say the queries are different or that Max is giving a Sum instead of the max value of a list or that you have to convert the IQueriable to a list before proceeding.