How go get max value of a unique id column using LINQ

↘锁芯ラ 提交于 2020-01-03 15:32:29

问题


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

SELECT        MAX(Game_id) AS MaxValue
FROM          Dim_Game

回答1:


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




回答2:


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




回答3:


you can also use a stored procedure like that :

 select ident_current('table_name')



回答4:


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


来源:https://stackoverflow.com/questions/8549413/how-go-get-max-value-of-a-unique-id-column-using-linq

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!