I'm creating a new module for a Data Migration and I notice that when I do a _repository.Insert or _repository.InsertAsync it's not retuning a Temp ID (-2147482647) anymore. If I use InsertAndGetId or InsertAndGetIdAsync it works fine but it's way to slow as I need to do thousands of inserts.
I used to be able to create a User, Insert, and then use the user.Id on child entities while inside the same method decorated with a [UnitOfWork] and at the end it would insert them all correctly. This behaviour seems to have changed somehow between version 7.0 and 8.4.
Can someone help?
3 Answer(s)
-
0
Hi @rfrcarvalho,
I didn't know that it was acting like that. Could that be changed between EF Core 2.x and 3.x ? If you are able to use GUID for PK, it might solve this problem for you.
-
0
Unfortunately it's not an option as it's the User table. I have a Persons table which is linked to a User table in the case the person needs to login into the system.
I see a lot of other people mentioning these ids with big negative values like -2147482647. Nobody else is having the same problem?
-
0
hi @rfrcarvalho
This is a breaking change of EF Core 3.0.
Temporary key values are no longer set onto entity instances
Old behavior
Before EF Core 3.0, temporary values were assigned to all key properties that would later have a real value generated by the database. Usually these temporary values were large negative numbers.
New behavior
Starting with 3.0, EF Core stores the temporary key value as part of the entity's tracking information, and leaves the key property itself unchanged.
Why
This change was made to prevent temporary key values from erroneously becoming permanent when an entity that has been previously tracked by some DbContext instance is moved to a different DbContext instance.
Mitigations
Applications that assign primary key values onto foreign keys to form associations between entities may depend on the old behavior if the primary keys are store-generated and belong to entities in the Added state. This can be avoided by:
Not using store-generated keys. Setting navigation properties to form relationships instead of setting foreign key values. Obtain the actual temporary key values from the entity's tracking information. For example, context.Entry(blog).Property(e => e.Id).CurrentValue will return the temporary value even though blog.Id itself hasn't been set.
see https://docs.microsoft.com/en-us/ef/core/what-is-new/ef-core-3.0/breaking-changes#-key-values-are-no-longer-set-onto-entity-instances