How to get the maximum value of a unique id column using LINQ

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

SELECT        MAX(Game_id) AS MaxValue
FROM          Dim_Game
+5
source share
4 answers

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

+5
source

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

"Casting the value type to" System.Int32 "failed because the materialized value is null. Either the parameter is a general result type or the query must use a type with a null value."

To avoid the error, you must direct the column to NULL, and the result from 0.

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

. "Int32" , null

+1

you can also use the stored procedure:

 select ident_current('table_name')
0
source

you can use the following code if authentication increment is enabled

Convert.ToInt32(_entities.Database.SqlQuery("SELECT IDENT_CURRENT('table') + IDENT_INCR('table')", new object[0]).FirstOrDefault())
Run codeHide result
0
source

All Articles