We use EF core to store a bulk of data with an auto-number primary key. The auto-number is an Identity column in Sql Server. When inserting a large amount of records with related children we encounter this error:
System.InvalidOperationException entity cannot be tracked because another instance with the same key value is already being tracked
The github bug that described the same bug: Adding multiple new entities at the same time results in System.InvalidOperationException entity cannot be tracked because another instance with the same key value is already being tracked #13937 The same message, but explicit no use of identity. This got us thinking.
Digging a little deeper we discovered that the TemporaryIntValueGenerator used in EF core used int.minvalue + 1000. That is the first temporary Id used in EF core to track newly created records with an Identity column. Our exception occurs with a large amount of record, maybe 1000? Would the identity value generated in Sql already be used as a temporary value? The identity columns we use start at -2147483648 (int.minvalue) and increase by 1.
We implemented our own TemporaryNumberValueGenerator that start with 214748364 (int.maxvalue / 10) and use that in the OnModelCreating override:
protected override void OnModelCreating(ModelBuilder m) { base.OnModelCreating(m); m.Entity<MY_TYPE>() .Property(x => x.Id) .HasValueGenerator<TemporaryIntValueGeneratorMaxValue>(); }