数据库表为空时如何从数据库中获取Max Id?

时间:2016-05-18 08:58:08

标签: c# sql-server entity-framework-5 asp.net-mvc-5

我有一张名为“GRNHDReturn'在我的数据库中。当表为空时,我想从表中获取Max ReturnId。我怎么能这样做?

GRNHDReturn数据库 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;
}

2 个答案:

答案 0 :(得分:1)

您可以通过以下代码行完成所需的一切:

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

如果没有记录,按DefaultIfEmpty()告诉EF返回0int的默认值)。

答案 1 :(得分:0)

public string getMax()
{
   GRNHDReturn grh = new GRNHDReturn();
   int? max = (from o in context.GRNHDReturns
                  select (int?)o.ReturnId).Max();
   if (max == 0 || max == null)
   {
      max = 1;
      calculatemax = "RN" + max.ToString();
   }
   else
   {
      int? nextmax = max + 1;
      calculatemax = "RN" + nextmax.ToString();
   }
   return calculatemax;
}

你可以试试这个。

相关问题