由于外键约束,实体框架迁移无法删除表

编程入门 行业动态 更新时间:2024-10-25 16:17:58
本文介绍了由于外键约束,实体框架迁移无法删除表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我已经将现有数据库反向工程为代码优先模型。一些表将保留,但大多数表将被删除,并为新版本完全重新构造。

I have reverse-engineered the existing database to the code-first model. Some tables are to be kept but most are to be removed and completely re-architected for the new version.

我删除了一些旧类及其映射和添加迁移。

I delete some old classes and their mapping and add-migration.

迁移看起来像这样:

public override void Up() { DropForeignKey("dbo.Bingo_Review", "BingoID", "dbo.Bingo"); DropForeignKey("dbo.Bingo_Review_Text", "BingoReviewID", "dbo.Bingo_Review"); DropForeignKey("dbo.Bingo_Bonus", "BingoID", "dbo.Bingo"); DropForeignKey("dbo.Bingo_Bonus_Amount", "BingoBonusID", "dbo.Bingo_Bonus"); DropIndex("dbo.Bingo_Bonus", new[] { "BingoID" }); DropIndex("dbo.Bingo_Review", new[] { "BingoID" }); DropIndex("dbo.Bingo_Review_Text", new[] { "BingoReviewID" }); DropIndex("dbo.Bingo_Bonus_Amount", new[] { "BingoBonusID" }); DropTable("dbo.Bingo_Bonus"); DropTable("dbo.Bingo"); DropTable("dbo.Bingo_Review"); DropTable("dbo.Bingo_Review_Text"); DropTable("dbo.Bingo_Bonus_Amount"); DropTable("dbo.Bingo_Bonus_Type"); }

但是,当我运行迁移时,在程序包管理器控制台中出现以下错误

However when I run the migration, I get the following error in package manager console.

Could not drop object 'dbo.Bingo_Bonus' because it is referenced by a FOREIGN KEY constraint.

当迁移在删除表之前应该已经删除了任何外键时,为什么会出现此错误命令?

Why do I get this error when the migration should have already dropped any foreign keys prior to the drop table command? Is there any way around this?

推荐答案

如果 dbo.Bingo_Bonus 表名称曾经更改过,或者如果外键关系中的任何列已更改,EF不会自动重命名外键约束以使其匹配。我有一个类似的问题,我不得不手动添加这样的行,因为 DropForeignKey()函数实际上并没有删除应该被删除的键:

If the dbo.Bingo_Bonus table name has ever changed, or if any of the columns in the foreign key relationships have changed, EF does not rename the foreign key constraints automatically to match. I had a similar problem and I had to manually add a line like this because the DropForeignKey() function was not actually deleting the key it was supposed to:

Sql(@"ALTER TABLE [dbo].[MyTable] DROP CONSTRAINT [FK_dbo.Constraint_Name_From_Before_Table_Change]");

更多推荐

由于外键约束,实体框架迁移无法删除表

本文发布于:2023-10-14 21:44:37,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1492302.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:实体   框架

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!