实体框架自动迁移主键
我已经继承了一个sql server数据库和一个使用自动迁移 Entity Framework 5.0 Code First 的ASP.Net MVC 4 Web应用程序。但是,以前的开发人员似乎忘了在其中一个表中添加主键。我现在正在尝试使用自动迁移来执行此操作,但是它不起作用,也没有错误,似乎忽略了命令。
I have inherited a sql server database and an ASP.Net MVC 4 web application which is using Entity Framework 5.0 Code First with Auto Migrations . However, it appears the previous developer forgot to add a Primary Key to one of the tables. I am now trying to do this using Auto Migrations, however, it is not working, no errors either, just seems to be ignoring the command.
表如下
public int CourseDateHistoryID { get; set; }
public int CourseDateID { get; set; }
public int Event { get; set; }
//public string testProp{ get; set; }
我的映射是这样的,尝试在 CourseDateHistoryID
And my mapping is like this to try and create the primary key on CourseDateHistoryID
this.HasKey(t => t.CourseDateHistoryID);
this.Property(t => t.CourseDateHistoryID)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
我以为可能连接字符串是错误的,所以我试图添加一个名为 testProp 使用自动迁移,但这样做很好。
I thought maybe the connection string was wrong or something, so I tried to add a dumby string property called testProp using auto migrations, but this worked fine.
任何人都有任何想法,为什么我无法设置 CourseDateHistoryID 作为PK使用自动迁移?
Would anyone have any ideas as to why I cannot set CourseDateHistoryID as the PK using auto migrations?
感谢任何帮助。
您可以尝试使用Update-Database -verbose命令手动更新数据库。它应该会显示您正在应用的迁移以及遇到的错误。
You can try manually updating the database using Update-Database -verbose command. It should show you the migration it's applying as well as the errors it encounters.
或者为什么不使用Add-Migration命令添加另一个迁移,并在那里手动添加主键,例如:
Or why not add another migration using the Add-Migration command and manually add primary key there, for example:
public partial class AddPrimaryKey : DbMigration
{
public override void Up()
{
AddPrimaryKey(table: "dto.table", column: "CourseDateHistoryID", name: "PK_CourseDateHistoryID");
}
public override void Down()
{
DropPrimaryKey(table: "dto.table", name: "PK_CourseDateHistoryID");
}
}
希望这有帮助。