5

How can I write this in the simplest way using LINQ?

SELECT        MAX(Game_id) AS MaxValue
FROM          Dim_Game
Jean-François Beaulieu
  • 4,305
  • 22
  • 74
  • 107

4 Answers4

5

Try context.Dim_Games.Max(g => g.Game_id);

NET3
  • 1,520
  • 1
  • 16
  • 25
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1

If your column is not nullable and result of you query is empty, you will receive the error

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

To avoid the error you should cast column to nullable and result coalesce with 0.

int max=(surveys.Max(g =>( int?)g.SurveyID) ?? 0);

See more details in The cast to value type 'Int32' failed because the materialized value is null

Community
  • 1
  • 1
Michael Freidgeim
  • 26,542
  • 16
  • 152
  • 170
0

you can also use a stored procedure like that :

 select ident_current('table_name')
0

you can use following code, if identity increment is on

Convert.ToInt32(_entities.Database.SqlQuery("SELECT IDENT_CURRENT('table') + IDENT_INCR('table')", new object[0]).FirstOrDefault())
Niraj
  • 1,782
  • 1
  • 22
  • 32