c# - 无法先从模型代码中删除 FK

标签 c# asp.net-mvc entity-framework entity-framework-migrations

我已经使用现有数据库的代码优先方法创建了一个 MVC 应用程序。

我注意到我的一个表不需要外键,所以我尝试删除它但我不断收到:

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

我完成的步骤

  • 进入BorrowedProperty类并删除 public int StatusId { get; set; } & public virtual codeStatu codeStatu { get; set; }
  • 进入CodeStatu类并删除 [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<BorrowedProperty> BorrowedProperties { get; set; }
  • 进入我的 DbContext 并注释掉这一行 //modelBuilder.Entity<codeStatu>() // .HasMany(e => e.BorrowedProperties) // .WithRequired(e => e.codeStatu) // .HasForeignKey(e => e.StatusId) // .WillCascadeOnDelete(false);
  • 添加-迁移 DeleteStatusFKFromBorrowedProperty

结果是:

public partial class DeleteStatusFKFromBorrowedProperty : DbMigration
{
    public override void Up()
    {
        DropForeignKey("dbo.BorrowedProperty", "StatusId", "dbo.codeStatus");
        DropIndex("dbo.BorrowedProperty", new[] { "StatusId" });
        DropColumn("dbo.BorrowedProperty", "StatusId");
    }

    public override void Down()
    {
        AddColumn("dbo.BorrowedProperty", "StatusId", c => c.Int(nullable: false));
        CreateIndex("dbo.BorrowedProperty", "StatusId");
        AddForeignKey("dbo.BorrowedProperty", "StatusId", "dbo.codeStatus", "Id");
    }
}
  • 更新数据库

然后我收到上面的错误。 BorrowedProperty 数据库表中有 条记录。

我做错了什么?

最佳答案

从异常消息中可以清楚地看出,您有名为 FK_BorrowedProperty_codeStatus 的外键约束,它可以防止 StatusId 列被删除。您可以创建一个包含 SQL 命令的方法来删除 FK 约束,如下所示:

private void DropForeignKeyConstraint()
{
    // This command may work if the constraint name is known:
    // Sql(@"ALTER TABLE [dbo].[BorrowedProperty] DROP CONSTRAINT [FK_BorrowedProperty_codeStatus]");

    Sql(@"DECLARE @constraint NVARCHAR(128)
        SELECT @constraint = name
        FROM sys.default_constraints
        WHERE parent_object_id = object_id(N'dbo.BorrowedProperty')
        AND col_name(parent_object_id, parent_column_id) = 'StatusId';
        IF @constraint IS NOT NULL
           EXECUTE('ALTER TABLE [dbo].[BorrowedProperty] DROP CONSTRAINT [' + @constraint + ']')");
}

将方法放在 Up 方法中的迁移代码中,如下所示:

public partial class DeleteStatusFKFromBorrowedProperty : DbMigration
{
    public override void Up()
    {
        DropForeignKeyConstraint(); // dropping FK constraint first
        DropForeignKey("dbo.BorrowedProperty", "StatusId", "dbo.codeStatus");
        DropIndex("dbo.BorrowedProperty", new[] { "StatusId" });
        DropColumn("dbo.BorrowedProperty", "StatusId"); // drop column at last
    }
}

或者,如果您有权访问 SSMS 实例,则直接运行此查询:

ALTER TABLE [dbo].[BorrowedProperty] DROP CONSTRAINT [FK_BorrowedProperty_codeStatus]

注意:您可以尝试注释掉 Down 方法中的所有代码行,看看是否没有重新创建外键约束。

之后,您可以在包管理器控制台中执行 Add-MigrationUpdate-Database 以应用上述更改。

类似问题:

The object 'DF__*' is dependent on column '*' - Changing int to double

How do I drop a column with object dependencies in SQL Server 2008?

Entity Framework Migrations can't drop table because of foreign key constraint

关于c# - 无法先从模型代码中删除 FK,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44684566/

相关文章:

c# - mvc 在 Action 中生成 javascript

asp.net-mvc - NHibernate可以使用纯DDD方法吗?

c# - 使用 lambda 表达式获取第一个项目属性

c# - 避免数据库调用以减少内存

c# - Unity - 如何让我的跳跃动画循环工作?

c# - 从 SQL Server 中检索 varbinary(MAX) 到 C# 中的 byte[]

c# - 在 C# 中使用 LINQ 计算百分位

c# - OleDbCommand 中的参数未更改

c# - 使用 ASP.NET MVC 中的自定义登录页面进行 Intranet Windows 身份验证

c# - 如何建立这种 EF 关系?