Marc-Arthur
Marc-Arthur

Reputation: 51

Attempting to insert an entity with an auto-incremented ID puts Entity Framework Core in a funky state

I think I ran across an interesting problem with Entity Framework Core 5 while doing a unit test on SQL Server. My tables are set to cascade deletions.

I have a parent table that I inserted a row into. Everything went fine.

Now I specifically inserted an entity in the child table with a value for the column Id and the parent ID as foreign key. The insert failed as expected with error

Cannot insert explicit value for identity column in table 'XXXXX' when IDENTITY_INSERT is set to OFF

Then things took a turn for the worse at that point.

I tried to delete the parent row. SQL Server yells at me that I still cannot insert into the child table while IDENTITY_INSERT is off. The same error I got with the invalid insert. I am surmising that the cascade deletion is kicking in but since I was not successful at inserting a row in the child table with the parent PK there should have been no issue.

Has anybody also run into such a problem before?

Upvotes: 0

Views: 110

Answers (1)

Marc-Arthur
Marc-Arthur

Reputation: 51

I will accept @IvanStoev's answer. It was a db context problem. I was using the same context for both operations and the entity was still in the cache. Entity Framework attempted to add the entity before it deleted it.

Upvotes: 1

Related Questions