Entity Framework The ALTER TABLE statement conflicted with the FOREIGN KEY constraint

后端 未结 11 1797
傲寒
傲寒 2021-02-01 00:34

On updating database in Entity Framework , Code first Migration, I am getting this error:

The ALTER TABLE statement conflicted with the FOREIGN KEY constr

11条回答
  •  情歌与酒
    2021-02-01 01:13

    I had this issue as well with defaultValue set, gave:

    "The object is dependent on column ALTER TABLE ALTER COLUMN failed because one or more objects access this column".

    Ended up move the AddForeignKey/DropForeignKey to a new migration and ran them in separate update-database commands (dont excecute both migrations in one command then it failed for me.)

        public override void Up()
        {
            CreateTable(
                "dbo.DecisionAccesses",
                c => new
                {
                    Id = c.Int(nullable: false),
                    Name = c.String(nullable: false, maxLength: 50),
                })
                .PrimaryKey(t => t.Id);
    
            CreateTable(
                "dbo.DecisionPersonStatus",
                c => new
                {
                    Id = c.Int(nullable: false),
                    Name = c.String(nullable: false, maxLength: 50),
                })
                .PrimaryKey(t => t.Id);
    
            AddColumn("dbo.DecisionForm_DecisionFields", "DecisionAccessId", c => c.Int(nullable: false, defaultValue: (int)DecisionAccess.Creator));
            AddColumn("dbo.DecisionMatterPersons", "DecisionPersonStatusId", c => c.Int(nullable: false, defaultValue: (int)DecisionAccess.Creator));
            CreateIndex("dbo.DecisionForm_DecisionFields", "DecisionAccessId");
            CreateIndex("dbo.DecisionMatterPersons", "DecisionPersonStatusId");
            //I moved outcommented to next migration and ran the migrations in separate steps to avoid: (The object is dependent on column ALTER TABLE ALTER COLUMN failed because one or more objects access this column)
            //AddForeignKey("dbo.DecisionForm_DecisionFields", "DecisionAccessId", "dbo.DecisionAccesses", "Id", cascadeDelete: true); 
            //AddForeignKey("dbo.DecisionMatterPersons", "DecisionPersonStatusId", "dbo.DecisionPersonStatus", "Id", cascadeDelete: true);
        }
    
    
        public override void Down()
        {
            //Moved to next migration
            //DropForeignKey("dbo.DecisionMatterPersons", "DecisionPersonStatusId", "dbo.DecisionPersonStatus");
            //DropForeignKey("dbo.DecisionForm_DecisionFields", "DecisionAccessId", "dbo.DecisionAccesses");
        }
    

提交回复
热议问题