1

I Have a model like this

public partial class TableNames
{

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

Then in a controller I'm Trying to get max IntIdfrom that model

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

When the table has no records (it's empty) , the controller throws this error

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.

How can I do to fix it ?

Juan Pablo Gomez
  • 5,203
  • 11
  • 55
  • 101

3 Answers3

3

Try this instead:

int? Max = max.AsQueryable().Max(x => (int?)x.IntId);
Splendor
  • 1,386
  • 6
  • 28
  • 62
3

If you do not wish to deal with Nullable and want a default value (based upon Splendor's code), you may do something similar to the following:

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

Trent
  • 335
  • 2
  • 8
0

try:

max.Where(i => i.IntId.HasValue).Select(i => i.IntId.Value).Max()
lante
  • 7,192
  • 4
  • 37
  • 57