添加你的第一次迁移

启用迁移后(请参阅此示例 ),你现在可以创建包含所有数据库表,索引和连接的初始创建的第一个迁移。

可以使用该命令创建迁移

Add-Migration <migration-name>

此命令将创建一个包含两个方法 UpDown 的新类,用于应用和删除迁移。

现在应用基于上面示例的命令来创建名为 Initial 的迁移 :

PM> Add-Migration Initial
Scaffolding migration 'Initial'.
The Designer Code for this migration file includes a snapshot of your current Code
First model. This snapshot is used to calculate the changes to your model when you
scaffold the next migration. If you make additional changes to your model that you 
want to include in this migration, then you can re-scaffold it by running 
'Add-Migration Initial' again.

创建一个新的文件时间戳 _Initial.cs(这里只显示重要的东西):

public override void Up()
{
   CreateTable(
       "dbo.Authors",
        c => new
           {
               AuthorId = c.Int(nullable: false, identity: true),
               Name = c.String(maxLength: 128),
           })
        .PrimaryKey(t => t.AuthorId);
        
    CreateTable(
       "dbo.BlogPosts",
       c => new
           {
                Id = c.Int(nullable: false, identity: true),
                Title = c.String(nullable: false, maxLength: 128),
                Message = c.String(),
                Author_AuthorId = c.Int(),
            })
        .PrimaryKey(t => t.Id)
        .ForeignKey("dbo.Authors", t => t.Author_AuthorId)
        .Index(t => t.Author_AuthorId);
}
    
public override void Down()
{
    DropForeignKey("dbo.BlogPosts", "Author_AuthorId", "dbo.Authors");
    DropIndex("dbo.BlogPosts", new[] { "Author_AuthorId" });
    DropTable("dbo.BlogPosts");
    DropTable("dbo.Authors");
}

如你所见,在方法 Up() 中创建了两个表 AuthorsBlogPosts,并相应地创建了字段。另外,通过添加字段 Author_AuthorId 来创建两个表之间的关系。另一方面,Down() 方法试图反转迁移活动。

如果你对迁移有信心,可以使用以下命令将迁移应用于数据库:

Update-Database

所有挂起的迁移(在本例中为 Initial -migration)都应用于数据库,然后应用种子方法(相应的示例)

PM> update-database
Specify the '-Verbose' flag to view the SQL statements being applied to the target     
database.
Applying explicit migrations: [201609302203541_Initial].
Applying explicit migration: 201609302203541_Initial.
Running Seed method.

你可以在 SQL 资源管理器中查看活动的结果: 数据库概述

对于命令 Add-MigrationUpdate-Database,有几个选项可用于调整活动。要查看所有选项,请使用

get-help Add-Migration

get-help Update-Database