您的列可以为空
int maxAge = context.Persons.Select(p => p.Age).Max() ?? 0;
您的列不可为空
int maxAge = context.Persons.Select(p => p.Age).Cast<int?>().Max() ?? 0;
在这两种情况下,您都可以使用第二个代码。如果使用DefaultIfEmpty
,则将在服务器上进行更大的查询。对于有兴趣的人,以下是EF6等效产品:
查询不 DefaultIfEmpty
SELECT
[GroupBy1].[A1] AS [C1]
FROM ( SELECT
MAX([Extent1].[Age]) AS [A1]
FROM [dbo].[Persons] AS [Extent1]
) AS [GroupBy1]
查询 DefaultIfEmpty
SELECT
[GroupBy1].[A1] AS [C1]
FROM ( SELECT
MAX([Join1].[A1]) AS [A1]
FROM ( SELECT
CASE WHEN ([Project1].[C1] IS NULL) THEN 0 ELSE [Project1].[Age] END AS [A1]
FROM ( SELECT 1 AS X ) AS [SingleRowTable1]
LEFT OUTER JOIN (SELECT
[Extent1].[Age] AS [Age],
cast(1 as tinyint) AS [C1]
FROM [dbo].[Persons] AS [Extent1]) AS [Project1] ON 1 = 1
) AS [Join1]
) AS [GroupBy1]