Reputation: 4510
I'm having trouble updating the database, when I apply the migration I'm getting this error:
The object 'PK_dbo.CostCenter' is dependent on column 'Id'.
ALTER TABLE DROP COLUMN Id failed because one or more objects access this column.
I just tried to add a virtual property (CostCenter) to this table to be able to get that data
[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; }
}
This is the CostCenter table
[Table("CostCenter")]
public class CostCenter
{
public int Id { get; set; }
public string Code { get; set; }
[Required]
public virtual Department Department { get; set; }
}
And another table related to Department
[Table("Cost")]
public class Cost
{
public int Id { get; set; }
...
public virtual Department Departament { get; set; }
public virtual Material Material { get; set; }
}
The only change I added was the CostCenter property on the Department table, this is what VS created on the migrations file
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);
}
}
I already have a relationship similar to this on other tables, so I don't know what's causing the problem this time
Upvotes: 5
Views: 6551
Reputation: 6834
Per suggested solution above, once you are in the production, dropping db won't be the case.
In my case,
Is this the best solution?
Was it fixed the issue?
Upvotes: 2
Reputation: 72
I faced similar issue and just remove all the previous migration files, create a new one and executed update-database command. If you can, also delete the database, Before it.
Upvotes: 3