gpt4 book ai didi

c# - 数据库表为空时如何从数据库中获取最大ID?

转载 作者:太空宇宙 更新时间:2023-11-03 12:46:00 24 4
gpt4 key购买 nike

我的数据库中有一个名为“GRNHDReturn”的表。当表为空时,我想从表中获取 Max ReturnId。我该怎么做?

GRNHD返回数据库 GRNHDReturn Database

public string getMax()
{
GRNHDReturn grh = new GRNHDReturn();
int max = 0;
if ((context.GRNHDReturns.Max(p => p.ReturnId) == 0))
{
max = 1;
calculatemax = "RN" + max.ToString();
}
else
{
max = context.GRNHDReturns.Max(p => p.ReturnId);
int nextmax = max + 1;
calculatemax = "RN" + nextmax.ToString();
}
return calculatemax;
}

最佳答案

你可以通过这些代码行做任何你想做的事情:

int max = 0;  
max = context.GRNHDReturns.Select(p => p.ReturnId)
.DefaultIfEmpty().Max();
int nextmax = max + 1;
calculatemax = "RN" + nextmax.ToString();
return calculatemax;

通过 DefaultIfEmpty(),您告诉 EF 在没有记录时返回 0(int 的默认值)。

关于c# - 数据库表为空时如何从数据库中获取最大ID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37294764/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com