Fix identity generation for columns in temporal history tables#37884
Fix identity generation for columns in temporal history tables#37884Abde1rahman1 wants to merge 2 commits intodotnet:mainfrom
Conversation
There was a problem hiding this comment.
Pull request overview
This PR addresses a SQL Server temporal-table migrations bug where IDENTITY was being generated for columns added to temporal history tables (which SQL Server disallows), causing migrations to fail when re-enabling SYSTEM_VERSIONING.
Changes:
- Updated
SqlServerMigrationsSqlGenerator.ColumnDefinitionto suppressIDENTITYgeneration for detected history tables. - Added a functional test asserting that
IDENTITYis not emitted when adding a column to a*Historytable name.
Reviewed changes
Copilot reviewed 2 out of 2 changed files in this pull request and generated 2 comments.
| File | Description |
|---|---|
| src/EFCore.SqlServer/Migrations/SqlServerMigrationsSqlGenerator.cs | Adds logic intended to skip IDENTITY when generating column SQL for temporal history tables. |
| test/EFCore.SqlServer.FunctionalTests/Migrations/SqlServerMigrationsSqlGeneratorTest.cs | Adds a test to validate that IDENTITY isn’t generated for a history-table column. |
You can also share your feedback on Copilot code review. Take the survey.
src/EFCore.SqlServer/Migrations/SqlServerMigrationsSqlGenerator.cs
Outdated
Show resolved
Hide resolved
test/EFCore.SqlServer.FunctionalTests/Migrations/SqlServerMigrationsSqlGeneratorTest.cs
Show resolved
Hide resolved
roji
left a comment
There was a problem hiding this comment.
This seems to leave the table without IDENTITY, meaning that subsequent inserts will fail because the key won't be database-generated, and therefore have the CLR default (0) and cause conflicts.
I'm not sure what the exact SQL Server limitations are here, but when creating a new temporal table there doesn't seem to be any issue with it having IDENTITY columns; I think a bit more investigation is needed here in order to understand what EF behavior makes sense.
|
@roji, The main point is that SQL Server strictly forbids adding IDENTITY to an existing history table; it throws an error because it expects the history table to be a passive sink that just stores values already generated by the main table. We don't need to worry about runtime conflicts because the main table will still have its IDENTITY property, and EF Core will continue to treat it as ValueGeneratedOnAdd. When a record is updated, SQL Server simply copies the generated ID into the history table. The fix is just to ensure the migration script doesn't try to mirror the IDENTITY behavior onto the history table, which is a physical requirement of the database engine. |
Summary of the changes
I have fixed the issue where IDENTITY was incorrectly generated for columns in Temporal History tables during migrations. I've updated SqlServerMigrationsSqlGenerator to skip identity generation when the target table is a history table.
Fixes #36025