I have a SQL Server database I mostly interact with using EF Core in a .NET project: I'll analogize my domain logic for simplicity.
I have a Fruits table holding general fruit data in columns Weight, Volume, Tastiness. But, due to inheritance, I also have a variety of other tables for specific fruit data (Grapes with Size, Squishiness; Bananas with Length, Girth, Curvature; Oranges with Acidity, Color).
At the beginning of my project, I decided to use a natural PK for Fruits called Name. To connect fruit type tables to the Fruits table, I made the PK of those tables an FK to Fruits.Name.
However, it's not unusual for users to enter the wrong fruit name and not realize until after they've already entered all the fruit data, so I decided I should finally give them the ability to update Fruits.Name. EF doesn't like this because once you change the PK it doesn't know what row it should be updating. This seems perfectly reasonable, so I decided I should change my PK to a surrogate.
My plan was to:
- Add an identity column
- Add a uniqueness constraint to my
Namecolumn - Remove the primary constraint from
Name - Add the primary constraint to the identity column
My hope was adding an explicit uniqueness constraint before removing the primary constraint would allow the foreign keys to be cool with the situation. Instead, I get an error
The constraint 'PK_Fruit' is being referenced by table 'Grapes', foreign key constraint 'FK_Grapes_Fruits'
My hypothesis is what I want to do can't be achieved without dropping the foreign keys and adding them back afterwards. The problem with this is there are a LOT of fruit types (way more than just Grapes, Bananas, and Oranges).
It makes sense to me the uniqueness constraint should be able to bypass the error.
How can I use a uniqueness constraint to bypass this error?