我有這樣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.
我該如何解決它?
也許'max.Where(X => x.HasValue)。最大(X => x.In tId)'? –
我想「AsQueryable()」不是必需的。嘗試刪除它。 –
這個問題的答案可能有所幫助:http://stackoverflow.com/questions/2165605/whats-the-neatest-way-to-achieve-minordefault-in-linq –