【发布时间】:2012-11-30 10:46:33
【问题描述】:
我有一个这样的模型
public partial class TableNames
{
public string Name { get; set; }
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int IntId { get; set; }
}
然后在控制器中,我试图从该模型中获取最大 IntId
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).Max(x => x.IntId)? -
我猜“AsQueryable()”不是必需的。尝试删除它。
-
这个问题的答案可能会有所帮助:stackoverflow.com/questions/2165605/…
-
没什么,我正在尝试您的建议,但 x 没有显示 HasValue。你建议我的答案是问我 IQueryable。
标签: asp.net asp.net-mvc entity-framework