SQL Server Entity Framework Code First - Deleting Column is blocked due to Foreign Key

jrcvhitl  于 2023-10-15  发布在  其他
关注(0)|答案(1)|浏览(105)

I am trying to delete a column from my table, I deleted that COLUMN from the model class and ran the migration commands, and this SQL script got generated:

DECLARE @var0 nvarchar(128)

SELECT @var0 = name
FROM sys.default_constraints
WHERE parent_object_id = object_id(N'dbo.PRODUCT)
  AND col_name(parent_object_id, parent_column_id) = 'ID_PRODUCT_PARENT';

IF @var0 IS NOT NULL
   EXECUTE('ALTER TABLE [dbo].[PRODUCT] DROP CONSTRAINT [' + @var0 + ']')

ALTER TABLE [dbo].[PRODUCT] 
    DROP COLUMN [ID_PRODUCT_PARENT]

INSERT [dbo].[__MigrationHistory]--------------------------------------------------XXXX

When I run the command update-database -Verbose , I get this error:

The object 'FK_PRODUCT_PRODUCT' is dependent on column 'ID_PRODUCT_PARENT'.
ALTER TABLE DROP COLUMN ID_PRODUCT_PARENT failed because one or more objects access this column

I checked the table, when I expanded the keys I see FK_PRODUCT_PRODUCT but not sure why the SQL is not generating the script to drop this key.

How do I fix this issue? I am worried that if I drop FK_PRODUCT_PRODUCT manually from the table it might cause issues.

When i tried right clicking the the key FK_PRODUCT_PRODUCT and viewing the script, it looks like below.

ALTER TABLE [dbo].[PRODUCT] WITH CHECK AND CONSTRAINT [FK_PRODUCT_PRODUCT] FOREIGN KEY([ID_PRODUCT_PARENT]) REFERENCES [dbo].[PRODUCT] ([ID_PRODUCT])
GO

ALTER TABLE [dbo].[PRODUCT] CHECK CONSTRAINT [FK_PRODUCT_PRODUCT]
GO
xtupzzrd

xtupzzrd1#

Since you want to drop the column ID_COLUMN_PARENT you will need to first drop the foreign key constraint FK_PRODUCT_PRODUCT . You eluded to knowing this in the question. This requires two statements.

alter table PRODUCT drop constraint FK_PRODUCT_PRODUCT;
alter table PRODUCT drop column ID_PRODUCT_PARENT;

In your question you sound concerned this may cause issues. Not sure what issues it may cause but they would be logical issues with the application, not with the database.

相关问题