EF Core 6 - Primary key incrementing problem

raysefo

Well-known member
Joined
Feb 22, 2019
Messages
361
Programming Experience
10+
Hello friends,

I am working on a Blazor Server application which is running on production for a while. There is an Orders table, user can insert records. Here is the table structure;

Orders:
     USE [InventoryManagement]
     GO
        
     /****** Object:  Table [dbo].[Orders]    Script Date: 9.01.2023 14:37:29 ******/
     SET ANSI_NULLS ON
     GO
        
     SET QUOTED_IDENTIFIER ON
     GO
        
     CREATE TABLE [dbo].[Orders](
      [Id] [int] IDENTITY(1,1) NOT NULL,
      [OrderDateTime] [datetime2](7) NOT NULL,
      [Status] [nvarchar](max) NOT NULL,
      [DoneBy] [nvarchar](50) NOT NULL,
      [CustomerId] [int] NOT NULL,
      CONSTRAINT [PK_Orders] PRIMARY KEY CLUSTERED
     (
      [Id] ASC
     )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
     ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
     GO
        
     ALTER TABLE [dbo].[Orders] ADD  DEFAULT ((0)) FOR [CustomerId]
     GO
        
     ALTER TABLE [dbo].[Orders]  WITH CHECK ADD  CONSTRAINT [FK_Orders_Customers_CustomerId] FOREIGN KEY([CustomerId])
     REFERENCES [dbo].[Customers] ([Id])
     ON DELETE CASCADE
     GO
        
     ALTER TABLE [dbo].[Orders] CHECK CONSTRAINT [FK_Orders_Customers_CustomerId]
     GO

The primary key is the Id column and auto-increment by 1.
Ekran görüntüsü 2023-01-09 144214.png


This Id column increased one by one for a while, then suddenly became 1100. (let's say from 45 - 1100) I checked the logs, and here are some of the insert statements.

C#:
2022-12-21 11:06:16.9792|0|DEBUG|Microsoft.EntityFrameworkCore.ChangeTracking|DetectChanges starting for 'IMSContext'.
 2022-12-21 11:06:16.9792|0|DEBUG|Microsoft.EntityFrameworkCore.ChangeTracking|DetectChanges completed for 'IMSContext'.
 2022-12-21 11:06:17.0001|0|DEBUG|Microsoft.EntityFrameworkCore.Database.Connection|Opening connection to database 'InventoryManagement' on server '.\SQLEXPRESS'.
 2022-12-21 11:06:17.0001|0|DEBUG|Microsoft.EntityFrameworkCore.Database.Connection|Opened connection to database 'InventoryManagement' on server '.\SQLEXPRESS'.
 2022-12-21 11:06:17.0001|0|DEBUG|Microsoft.EntityFrameworkCore.Database.Transaction|Beginning transaction with isolation level 'Unspecified'.
 2022-12-21 11:06:17.0001|0|DEBUG|Microsoft.EntityFrameworkCore.Database.Transaction|Began transaction with isolation level 'ReadCommitted'.
 2022-12-21 11:06:17.0305|0|DEBUG|Microsoft.EntityFrameworkCore.Database.Command|Creating DbCommand for 'ExecuteReader'.
 2022-12-21 11:06:17.0305|0|DEBUG|Microsoft.EntityFrameworkCore.Database.Command|Created DbCommand for 'ExecuteReader' (0ms).
 2022-12-21 11:06:17.0305|0|DEBUG|Microsoft.EntityFrameworkCore.Database.Command|Executing DbCommand [Parameters=[@p0='?' (DbType = Int32), @p1='?' (Size = 50), @p2='?' (DbType = DateTime2), @p3='?' (Size = 4000)], CommandType='Text', CommandTimeout='30']
 SET NOCOUNT ON;
 INSERT INTO [Orders] ([CustomerId], [DoneBy], [OrderDateTime], [Status])
 VALUES (@p0, @p1, @p2, @p3);
 SELECT [Id]
 FROM [Orders]
 WHERE @@ROWCOUNT = 1 AND [Id] = scope_identity();
 2022-12-21 11:06:17.0305|0|INFO|Microsoft.EntityFrameworkCore.Database.Command|Executed DbCommand (2ms) [Parameters=[@p0='?' (DbType = Int32), @p1='?' (Size = 50), @p2='?' (DbType = DateTime2), @p3='?' (Size = 4000)], CommandType='Text', CommandTimeout='30']
 SET NOCOUNT ON;
 INSERT INTO [Orders] ([CustomerId], [DoneBy], [OrderDateTime], [Status])
 VALUES (@p0, @p1, @p2, @p3);
 SELECT [Id]
 FROM [Orders]
 WHERE @@ROWCOUNT = 1 AND [Id] = scope_identity();
 2022-12-21 16:06:46.6661|0|INFO|Microsoft.EntityFrameworkCore.Database.Command|Executed DbCommand (1ms) [Parameters=[@p0='?' (DbType = Int32), @p1='?' (Size = 50), @p2='?' (DbType = DateTime2), @p3='?' (Size = 4000)], CommandType='Text', CommandTimeout='30']
 SET NOCOUNT ON;
 INSERT INTO [Orders] ([CustomerId], [DoneBy], [OrderDateTime], [Status])
 VALUES (@p0, @p1, @p2, @p3);
 SELECT [Id]
 FROM [Orders]
 WHERE @@ROWCOUNT = 1 AND [Id] = scope_identity();
 2022-12-21 16:06:46.6661|0|DEBUG|Microsoft.EntityFrameworkCore.ChangeTracking|The foreign key property 'Order.Id' was detected as changed. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see property values.

Here is the Order entity:
C#:
     public class Order
         {
             public int Id { get; set; }
                
             [Required]
             public DateTime OrderDateTime { get; set; }
             [Required]
             [MaxLength(250)]
             public int CustomerId { get; set; }
             public string Status { get; set; }
             [MaxLength(50)]
             public string DoneBy { get; set; }
             public List<OrderDetail> OrderDetails { get; set; }
             public Customer Customer { get; set; }
        
        
         }

What is the reason that Id did not increment 1 by 1? Is this a bug?

Thank you.
 
Solution
And

and

And

and

 
Solution
It shouldn't matter; if it does, your expectations are wrong or your code is wrong.

Assign no meaning to SQLS PK values, do not show them to the user, do not look at them yourself and do not care what they are. Care only that they help two records, in two different tables, stay related

There is no bug, and if you have some inner OCD that they must be sequential you can either work on getting over it or use GUIDs as your primary key (I recommend the former)
 
It shouldn't matter; if it does, your expectations are wrong or your code is wrong.

Assign no meaning to SQLS PK values, do not show them to the user, do not look at them yourself and do not care what they are. Care only that they help two records, in two different tables, stay related

There is no bug, and if you have some inner OCD that they must be sequential you can either work on getting over it or use GUIDs as your primary key (I recommend the former)
Indeed. If it was actually a problem, Microsoft wouldn't have made it happen in the first place. I'm not saying that it's shouldn't be alarming when you see it happen for the first time but, once you have investigated and determined that it is normal, that should be the end of it. It's quite possible for an identity to end up with gaps for other reasons and there's also no requirement for Microsoft to keep making identities ascending in future versions, even though they almost certainly will. If you need an actual sequential ID, use a sequence rather than an identity.
 
Back
Top Bottom