'Alternative for c# .Last
Currently I am using .Last to find the last number in a database and then assign the incoming information a number that is plus one higher the last number.
var newId = (_logs.Last().RecordID + 1);
I was wondering if there's a different way of looking for the highest number and then adding one to that number for the new id.
Edit:
Saw a few responses and realised I didn't make it clear what database I'm using. I'm using an in-memory repository.
Solution 1:[1]
If you can't use a identity Id column. You can get the last id, by just request it from the database
var lastId = context.Table
.OrderByDescending(x => x.Id)
.Select(x => x.Id)
.FirstOrDefault();
Solution 2:[2]
As Fabjian said in the comments, if you are using SQL Server, you should set the column as an Identity Column and then the ID will increment automatically. If you alter that, you new the ID of the inserted line you should terminate the query with: SELECT SCOPE_IDENTITY()
; this will return you the ID of the line inserted.
If you only need to know the last ID of a table you can query with
SELECT IDENT_CURRENT('TABLE_NAME')
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Darkk L |
Solution 2 | Jeremy Caney |