EF core: entity cannot be tracked

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>();
}

About erictummers

Working in a DevOps team is the best thing that happened to me. I like challenges and sharing the solutions with others. On my blog I’ll mostly post about my work, but expect an occasional home project, productivity tip and tooling review.
This entry was posted in Development, Tooling and tagged , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.