【问题标题】:How to get Max Id from database when database table is empty?数据库表为空时如何从数据库中获取Max Id?
【发布时间】:2016-05-18 08:58:07
【问题描述】:

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

GRNHDR返回数据库

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;
}

【问题讨论】:

  • 尝试:SELECT ISNULL(MAX(RowID), 0) FROM Table ?
  • @A.格林史密斯:select coalesce(max(t.RowID), 0) from MyTable t - SQL-92 兼容
  • 我想获取问题中显示的代码的 ID,而不是 sql 查询。
  • 您的 ID 列是否启用了身份验证
  • 它是一个自动生成的 Id,它不能为空

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


【解决方案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 的默认值)。

【讨论】:

    【解决方案2】:
    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;
    }
    

    你可以试试这个。

    【讨论】:

      猜你喜欢
      • 2020-10-10
      • 2021-11-09
      • 1970-01-01
      • 2017-11-01
      • 2019-12-03
      • 2016-03-11
      • 2019-05-26
      • 2017-12-24
      • 1970-01-01
      相关资源
      最近更新 更多