问题
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.
The table is like this
public int CourseDateHistoryID { get; set; }
public int CourseDateID { get; set; }
public int Event { get; set; }
//public string testProp{ get; set; }
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);
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.
Would anyone have any ideas as to why I cannot set CourseDateHistoryID as the PK using auto migrations?
Thanks for any help.
回答1:
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.
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");
}
}
Hope this helps.
来源:https://stackoverflow.com/questions/17295662/entity-framework-auto-migrations-primary-key