Entity Framework SQL Server increments an Id Key out of order if previous values are available

I have an MVC4 website and it has a SQL Server DB that contains its posts. On each post there is a Next and Previous button. These buttons are calculated from databaseContext.Post.Count() plus or minus 1 and (if item = zero don't display Previous, and the other way round.) However due to some Posts being deleted there are some spots in between that are null. This doesn't bother me except now for some reason the DB has been adding new entries to these empty spots, so the Count() vs what is actualy their is off and this causes the highest value's next to point to a higher value than what actually exists (since it is over the total count, keep in mind that even its Id is over the total count.)

I know I can programmatically check for this type of issue however I was wondering if there a way to change how the Id keys are created?

Answers


You are assuming that a generated ID will be dense monotonous, with no gaps. This is incorrect assumption. There will always be gaps in the generated IDs. You can never assume that counting the records will give you valid IDs. If you want a dense, monotonous row number use the dedicated ROW_NUMBER function, but leveraging this for navigation is problematic.


Need Your Help

Sorting an array of valid and invalid numbers in c++ for an embedded system

c++ c algorithm sorting embedded

I am writing a program in C++ that will be used with Windows Embedded Compact 7. I have heard that it is best not to dynamically allocate arrays when writing embedded code. I will be keeping track of

JQuery list / link manipulation error in IE7 only

jquery jquery-ui internet-explorer-7 jquery-ui-dialog

I use the following code to find hooks in the html, generate links from them, create and populate popups, and then hide the hooks themselves from view. It works fine in FF, Chrome, Safari, IE8 and ...