[SOLVED] Organizing Primary Key Value(int) with EF Core

Issue

This Content is from Stack Overflow. Question asked by Ozan Tosun

Hello i am having trouble with delete command on EF code first. When i remove one data and after add another data,my primary key value changes. For example: 1-2-3-4-5 and i remove id =5 and add another data primary key changes 6 and it’s look like 1-2-3-4-6. Thank you.

private void silToolStripMenuItem_Click(object sender, EventArgs e)
        {
            int id = (int)dgvTurler.SelectedRows[0].Cells[0].Value;
            Tur bulunacakTur = db.Turler.FirstOrDefault(a => a.Id == id);
            
            db.Turler.Remove(bulunacakTur);           
            db.SaveChanges();
            
        } 



Solution

That is just generally the behaviour of auto-incremented IDs in SQL Server, no good way around that.

I’d say it is also generally the preferred way of doing automatic IDs, to prevent confusion between the record with ID of 5 that you deleted previously and a new record with the same ID.

About this topic in SQL Server docs:
https://learn.microsoft.com/en-us/sql/t-sql/statements/create-table-transact-sql-identity-property?view=sql-server-ver16#remarks


This Question was asked in StackOverflow by Ozan Tosun and Answered by Andrejs Ķīlis It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?