如何从数据库中删除具有约束条件的列(ASP.NET MVC5)

时间:2018-02-23 06:43:30

标签: sql-server tsql asp.net-mvc-5 entity-framework-6 ef-migrations

每次我尝试使用以下迁移删除列时:

public partial class RemoveProject_Id1InAspNetUsers2 : DbMigration
    {
        public override void Up()
        {
            DropColumn("dbo.AspNetUsers", "Project_Id1");
        }

        public override void Down()
        {
        }
    }

我在PMC Update-Database之后收到以下错误:

The index 'IX_Project_Id1' is dependent on column 'Project_Id1'.
The object 'FK_dbo.AspNetUsers_dbo.Projects_Project_Id1' is dependent on column 'Project_Id1'.
ALTER TABLE DROP COLUMN Project_Id1 failed because one or more objects access this column.

这是我的AspNetUser表: dbo.AspNetUser DB Image

这是我的项目类:

public class Project
{
    public int Id { get; set; }

    [DisplayName("Project Manager")]
    public string ProjectManagerId { get; set; }

    //        [ForeignKey("ProjectManagerId")]
    //        public ApplicationUser ProjectManager { get; set; }

    //public string ProjectMembersId { get; set; }

    //public List<ApplicationUser> ProjectMembers { get; set; }

    public virtual ICollection<ProjectResource> OurProjectResources { get; set; }

}

我尝试从我的Project Class中删除删除ApplicationUser的所有引用。

PS:我尝试过运行此SQL语句的迁移: Sql("ALTER TABLE AspNetUsers DROP CONSTRAINT FK_AspNetUsers_Projects_Project_Id1");,它会出错:

'FK_AspNetUsers_Projects_Project_Id1' is not a constraint.
Could not drop constraint. See previous errors.

我正在使用EF6 Code First Workflow。

This post解释了问题所在,但我想了解如何编写迁移以从数据库中删除列。

1 个答案:

答案 0 :(得分:1)

首先,您需要在错误中指定约束名称:

  

'FK_AspNetUsers_Projects_Project_Id1'不是约束。不能   下降约束。查看以前的错误。

因此,要删除约束,我们可以使用:

Sql("ALTER TABLE AspNetUsers DROP CONSTRAINT [FK_dbo.AspNetUsers_dbo.Projects_Project_Id1]");

然后,您会收到错误,即在该字段上创建了索引:

  

索引'IX_Project_Id1'依赖于列'Project_Id1'。改变   TABLE DROP COLUMN Project_Id1因一个或多个对象而失败   访问此列。

我们也需要删除索引。

Sql("DROP INDEX [IX_Project_Id1] ON dbo.AspNetUsers ");