2016-05-18 52 views
2

我在我的数据库中有一个名为'GRNHDReturn'的表。我想在表格为空时从表格中获取最大返回ID。我怎样才能做到这一点?如何在数据库表为空时从数据库获取最大ID?

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

尝试:SELECT ISNULL(MAX(RowID),0)FROM Table? –

+2

@A。 Greensmith:'从MyTable t'选择合并(max(t.RowID),0) - SQL-92分区 –

+0

我想让我的问题显示的代码为Id,而不是sql查询。 –

回答

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

你可以试试这个。

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返回0(默认为int),如果没有记录。

相关问题