我在更新数据库时遇到问题,当我应用迁移时遇到此错误:
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; }
}
我添加的唯一更改是部门表上的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);
}
}
我已经在其他桌子上建立了类似的关系,所以我不知道这次导致问题的原因
答案 0 :(得分:1)
我面临类似的问题,只需删除所有以前的迁移文件,创建一个新文件并执行update-database命令。如果可以,也删除数据库,在它之前。
答案 1 :(得分:0)
根据上述建议的解决方案,一旦投入生产,就不会删除db。
就我而言
这是最好的解决方案吗?
它解决了这个问题吗?