2015-07-19 53 views
2

我無法更新數據庫,當我申請我得到這個錯誤遷移:EF代碼優先遷移ALTER TABLE DROP列ID失敗,因爲一個或多個對象訪問此列

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

我只是想給虛擬財產(CostCenter)添加到這個表能夠獲得這些數據

[Table("Department")] 
public class Department 
{ 
    public int Id { get; set; } 

    public string Code { get; set; } 

    public virtual IList<Cost> Costs_Department { get; set; } 
    public virtual CostCenter CostCenter { get; set; } 
} 

這是CostCenter表

[Table("CostCenter")] 
public class CostCenter 
{ 
    public int Id { get; set; } 

    public string Code { get; set; } 

    [Required] 
    public virtual Department Department { get; set; } 
} 

以及有關部

[Table("Cost")] 
public class Cost 
{ 
    public int Id { get; set; } 

    ... 

    public virtual Department Departament { get; set; } 
    public virtual Material Material { get; set; } 
} 

另一個表我說是在Department表的CostCenter屬性唯一的變化,這是VS的遷移創建的文件

public partial class CC : DbMigration 
{ 
    public override void Up() 
    { 
     DropForeignKey("dbo.CostCenter", "Department_CostCenter_Id", "dbo.Department"); 
     DropIndex("dbo.CostCenter", new[] { "Department_CostCenter_Id" }); 
     DropColumn("dbo.CostCenter", "Id"); 
     RenameColumn(table: "dbo.CostCenter", name: "Department_CostCenter_Id", newName: "Id"); 
     DropPrimaryKey("dbo.CostCenter"); 
     AlterColumn("dbo.CostCenter", "Id", c => c.Int(nullable: false)); 
     AddPrimaryKey("dbo.CostCenter", "Id"); 
     CreateIndex("dbo.CostCenter", "Id"); 
     AddForeignKey("dbo.CostCenter", "Id", "dbo.Department", "Id"); 
    } 

    public override void Down() 
    { 
     DropForeignKey("dbo.CostCenter", "Id", "dbo.Department"); 
     DropIndex("dbo.CostCenter", new[] { "Id" }); 
     DropPrimaryKey("dbo.CostCenter"); 
     AlterColumn("dbo.CostCenter", "Id", c => c.Int(nullable: false, identity: true)); 
     AddPrimaryKey("dbo.CostCenter", "Id"); 
     RenameColumn(table: "dbo.CostCenter", name: "Id", newName: "Department_CostCenter_Id"); 
     AddColumn("dbo.CostCenter", "Id", c => c.Int(nullable: false, identity: true)); 
     CreateIndex("dbo.CostCenter", "Department_CostCenter_Id"); 
     AddForeignKey("dbo.CostCenter", "Department_CostCenter_Id", "dbo.Department", "Id", cascadeDelete: true); 
    } 
} 

我已經有一個關係類似於其他表格,所以我不知道是什麼原因造成這個問題

回答

1

我面臨類似的問題,只是刪除所有以前的遷移文件,創建一個新的執行更新數據庫c ommand。如果可以的話,還要刪除數據庫,在它之前。

+0

歡迎來到SO。你能詳細說明一下嗎?也許寫出實現這個所需的命令。我認爲這會讓你的答案更容易被其他用戶重現。乾杯:) – m00am

+0

我忘記了這個問題,如果我沒有記錯,那就是我所做的,我不得不刪除一些以前的遷移並重新創建數據庫。謝謝! –

+6

對於已經投入生產的系統來說,這並不是真正的選擇。 –

相關問題