2012-12-12 21 views
1

我有這樣LINQ最大返回null瓦爾

public partial class TableNames 
{ 

    public string Name { get; set; } 
    [Key] 
    [DatabaseGenerated(DatabaseGeneratedOption.None)] 
    public int IntId { get; set; } 
} 

然後在控制器我試圖獲得最大的IntIdfrom該模型

var max = from c in db.TableNames 
      select c; 

int? Max = max.AsQueryable().Max(x => x.IntId); //This isntruction throws an error 
int IntId = (Max == null ? 1 : Max + 1); 

當表中沒有記錄(這是一個模型空),控制器拋出這個錯誤

The cast to value type 'Int32' failed because the materialized value is null. 
Either the result type's generic parameter or the query must use a nullable type. 

我該如何解決它?

+0

也許'max.Where(X => x.HasValue)。最大(X => x.In tId)'? –

+0

我想「AsQueryable()」不是必需的。嘗試刪除它。 –

+0

這個問題的答案可能有所幫助:http://stackoverflow.com/questions/2165605/whats-the-neatest-way-to-achieve-minordefault-in-linq –

回答

3

試試這個:

int? Max = max.AsQueryable().Max(x => (int?)x.IntId); 
+0

優秀.. Tks。您的幫助。 –

0

嘗試:

max.Where(i => i.IntId.HasValue).Select(i => i.IntId.Value).Max() 
3

如果你不希望處理可空,並需要有一個默認值(基於蝶舞的代碼),你可能會做同樣的事情以下內容:

int Max = max.AsQueryable().Max(x => (int?)x.IntId) ?? 1;