This code
int maxTrackId = dataContext.TicketTracks.Max(T => T.TrackId);
Generates the following SQL code:
SELECT MAX([t0].[TrackId]) AS [value]
FROM [dbo].[TicketTracks] AS [t0]
But if the table is empty, I got an exception saing that nullable value cannot be assigned to non-nullable variable.
Then I write this code, explicitly telling the SQL provider that i need either maximum or null:
int? maxTrackId = dataContext.TicketTracks.Max(T => (int?)T.TrackId);
And it works fine on that non-nullable SQL column, giving me back either null or the number. But the SQL code generated is kind of strange:
SELECT MAX([t1].[value]) AS [value]
FROM (
SELECT [t0].[TrackId] AS [value]
FROM [dbo].[TicketTracks] AS [t0]
) AS [t1]
So it seems weird, especially with two SELECTs. Is there any way to circumvent this?
The SQL might be convoluted but there is no performance difference. The SQL Server query optimizer reliably optimizes both statements to the same plan.
Really, removing a redundant nested select is a trivial case. I have never seen this cause a plan difference.
So it is an aesthetic problem, not a practical one. ORMs generate convoluted code and I learned to live with it.