Entity Framework Auto Migrations Primary Key

♀尐吖头ヾ 提交于 2020-01-07 04:55:13

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!