这段代码
int maxTrackId = dataContext.TicketTracks.Max(T => T.TrackId);
生成以下SQL
代码:
SELECT MAX([t0].[TrackId]) AS [value]
FROM [dbo].[TicketTracks] AS [t0]
但是如果表是空的,我会得到一个异常,即不能将可空值分配给不可为空的变量。
然后我编写这段代码,明确告诉 SQL 提供程序我需要最大值或空值:
int? maxTrackId = dataContext.TicketTracks.Max(T => (int?)T.TrackId);
它在那个不可为空的 SQL 列上工作正常,给我一个null
或一个数字。但是SQL
生成的代码有点奇怪:
SELECT MAX([t1].[value]) AS [value]
FROM (
SELECT [t0].[TrackId] AS [value]
FROM [dbo].[TicketTracks] AS [t0]
) AS [t1]
所以这看起来很奇怪,尤其是有两个SELECT
s。有什么办法可以规避这种情况吗?