实体框架程序包管理器控制台问题

时间:2018-09-10 03:23:09

标签: c# entity-framework

我有EF 5,我添加了下表,并且添加成功,如代码片段1所示。但是,我希望 UserID 是引用 Users 表的外键,如果我这样做了,那么我的代码应该像代码片段#2。 在不删除此新表的情况下,能否请您告诉我现在如何使UserID成为引用Users表的外键。非常感谢。我正在使用 Package Manager Console 来实现这一目标。

代码段1

public partial class Initialignorechanges : DbMigration
{
    public override void Up()
    {
        CreateTable(
            "dbo.Favorite",
            c => new
            {
                ID = c.Int(nullable: false, identity: true),
                UserID = c.Int(nullable: false),
                UserName = c.String(nullable: true, maxLength: 25, unicode: false),
                FavoritedUserID = c.Int(nullable: false),
                FavoritedUserName = c.String(nullable: true, maxLength: 25, unicode: false),
                FavoritedDate = c.DateTime(),
                ShowToUser = c.Boolean(nullable: false),
                ShowToFavoritedUser = c.Boolean(nullable: false),
            })
            .PrimaryKey(t => t.ID);                
    }

    public override void Down()
    {            
        DropTable("dbo.Favorite");
    }
}

代码段2:

public partial class Initialignorechanges : DbMigration
{
    public override void Up()
    {
        CreateTable(
            "dbo.Favorite",
            c => new
            {
                ID = c.Int(nullable: false, identity: true),
                UserID = c.Int(nullable: false),
                UserName = c.String(nullable: true, maxLength: 25, unicode: false),
                FavoritedUserID = c.Int(nullable: false),
                FavoritedUserName = c.String(nullable: true, maxLength: 25, unicode: false),
                FavoritedDate = c.DateTime(),
                ShowToUser = c.Boolean(nullable: false),
                ShowToFavoritedUser = c.Boolean(nullable: false),
            })
            .PrimaryKey(t => t.ID)
            .ForeignKey("dbo.Users", t => t.UserID, cascadeDelete: true)
            .Index(t => t.UserID);
    }

    public override void Down()
    {
        DropIndex("dbo.Favorite", new[] { "UserID" });
        DropForeignKey("dbo.Favorite", "UserID", "dbo.Users");
        DropTable("dbo.Favorite");
    }
}

1 个答案:

答案 0 :(得分:0)

看看Code-Based Migration in Entity Framework 6

  

现在,您必须使用Add-Migration创建一个迁移类。   带有迁移类名称的命令,如下所示。

enter image description here

  

使用add-migration命令创建迁移文件后,   必须更新数据库。执行Update-Database命令以   创建或修改数据库架构。使用–verbose选项查看   应用于目标数据库的SQL语句。

enter image description here

  

此时,将创建或更新数据库。现在,每当   您更改域类,使用名称执行Add-Migration   参数以创建新的迁移文件,然后执行   Update-Database命令将更改应用到数据库架构。