简体   繁体   English

如何选择linq-to-sql MAX查询?

[英]How to do one-select linq-to-sql MAX query?

This code 这段代码

int maxTrackId = dataContext.TicketTracks.Max(T => T.TrackId);

Generates the following SQL code: 生成以下SQL代码:

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: 然后,我编写此代码,明确告诉SQL提供程序我需要最大值或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. 它在该不可为空的SQL列上运行良好,可以返回null或数字。 But the SQL code generated is kind of strange: 但是生成的SQL代码有点奇怪:

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 SELECT s. 因此,这似乎很奇怪,尤其是对于两个SELECT Is there any way to circumvent this? 有什么办法可以避免这种情况?

The SQL might be convoluted but there is no performance difference. SQL可能很复杂,但是没有性能差异。 The SQL Server query optimizer reliably optimizes both statements to the same plan. SQL Server查询优化器可靠地将两个语句优化为同一计划。

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. ORM生成复杂的代码,我学会了使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM