我正在使用EF代码第一个datacontext,我正在寻找一种方法来获得给定实体集合的主键字段的最高值,这比我的更优雅。
目前我正在使用以下内容:
internal long GetHighestIdForProductGroups()
{
//s200 is the name of my data context
long stored = s200.ProductGroups.Count()> 0? s200.ProductGroups.Max(x => x.ProductGroupID) : 0;
var local = s200.ProductGroups.Local.Count() > 0 ? s200.ProductGroups.Max(x => x.ProductGroupID) :0;
return Math.Max(stored, local);
}
这可以在生成数据库之前调用,数据库中是否有一些数据,还有本地缓存中的一些数据或没有数据......
答案 0 :(得分:0)
投射到Nullable<int>
会使这至少缩短一点:
long stored = s200.ProductGroups.Max(p => (int?)p.ProductGroupID) ?? 0;
long local = s200.ProductGroups.Local.Max(p => (int?)p.ProductGroupID) ?? 0;
var max = Math.Max(stored, local);
如果集合为空,则在可空字段上使用Max
将返回null
。
还可以使用连接ID获取组合最大值,将本地ID发送到服务器并让数据库评估最大值:
var max = s200.ProductGroups
.Select(p => p.ProductGroupID)
.Concat(s200.ProductGroups.Local
.Select(p => p.ProductGroupID)
.ToArray())
.Max(id => (int?) id)
?? 0;
这实际上有效,但是对于ID为20和24的两个本地项,它会生成以下SQL:
SELECT
[GroupBy1].[A1] AS [C1]
FROM ( SELECT
MAX([UnionAll2].[ProductGroupID]) AS [A1]
FROM (SELECT
[Extent1].[ProductGroupID] AS [ProductGroupID]
FROM [dbo].[ProductGroups] AS [Extent1]
UNION ALL
SELECT
[UnionAll1].[C1] AS [C1]
FROM (SELECT
20 AS [C1]
FROM ( SELECT 1 AS X ) AS [SingleRowTable1]
UNION ALL
SELECT
24 AS [C1]
FROM ( SELECT 1 AS X ) AS [SingleRowTable2]) AS [UnionAll1]) AS [UnionAll2]
) AS [GroupBy1]
没有人会想要那个。