ef migration 使用

一 migration的使用
命令一共有5种,每个有两种写法:
参考 https://www.cnblogs.com/nsky/p/10323415.html
dotnet ef database drop 删除库

  dotnet ef migrations add initialCreate ||  Add-Migrantion (执行此命令项目生成一个目录(Migrations))

  dotnet ef database update     ||  Update-Database (把当前的Migrations更新到数据库中)

  dotnet ef migrations remove      ||  Remove-Migration (删除一个最新的Migrations,降级,根据数据库表结构删除migrations文件夹下面多余的文件)

  dotnet ef database update LastGoodMigration     ||     Update-Database LastGoodMigration(指定一个Migrations更新 LastGoodMigration 指定的migration名称)

  dotnet ef migrations script       ||   Script-Migration   (将更新内容生成sql脚本语句)

dotnet ef migratoins remove 是移除最新的一个migration,remove一次就移除一次

 dotnet ef migrations script -o d:\script\user.sql  

二 migrationBuilder命令
'''script
1
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Club",
columns: table => new
{
Id = table.Column(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
Name = table.Column(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Club", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Team",
columns: table => new
{
Id = table.Column(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
ClubId = table.Column(nullable: false),
Name = table.Column(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Team", x => x.Id);
table.ForeignKey(
name: "FK_Team_Club_ClubId",
column: x => x.ClubId,
principalTable: "Club",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
}

2

protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.EnsureSchema("mab");
migrationBuilder.CreateTable(
name: "MicroAggression",
schema: "mab",
columns: table => new
{
Aggression = table.Column(nullable: false),
Aggressiveness = table.Column(nullable: false),
Created = table.Column(nullable: false),
_Alternatives = table.Column(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_MicroAggression", x => x.Aggression);
});
migrationBuilder.CreateTable(
name: "Offense",
schema: "mab",
columns: table => new
{
Id = table.Column(nullable: false),
Offenses = table.Column(nullable: false),
User = table.Column(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Offense", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Correction",
schema: "mab",
columns: table => new
{
Id = table.Column(nullable: false),
Created = table.Column(nullable: false),
MicroAggressionId = table.Column(nullable: true),
OffenseId = table.Column(nullable: false),
Tweet = table.Column(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Correction", x => x.Id);
table.ForeignKey(
name: "FK_Correction_MicroAggression_MicroAggressionId",
column: x => x.MicroAggressionId,
principalSchema: "mab",
principalTable: "MicroAggression",
principalColumn: "Aggression",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_Correction_Offense_OffenseId",
column: x => x.OffenseId,
principalSchema: "mab",
principalTable: "Offense",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
}

3
public override void Up(MigrationBuilder migration)
{
migration.CreateTable(
name: "Blog",
columns: table => new
{
BlogId = table.Column(type: "int", nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", "IdentityColumn"),
Url = table.Column(type: "nvarchar(max)", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Blog", x => x.BlogId);
});
migration.CreateTable(
name: "Post",
columns: table => new
{
PostId = table.Column(type: "int", nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", "IdentityColumn"),
BlogId = table.Column(type: "int", nullable: false),
Content = table.Column(type: "nvarchar(max)", nullable: true),
Title = table.Column(type: "nvarchar(max)", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Post", x => x.PostId);
table.ForeignKey(
name: "FK_Post_Blog_BlogId",
columns: x => x.BlogId,
referencedTable: "Blog",
referencedColumn: "BlogId");
});
}

4
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Manufacturer",
columns: table => new
{
Id = table.Column(isNullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerIdentityStrategy.IdentityColumn),
Name = table.Column(isNullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Manufacturer", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Model",
columns: table => new
{
Id = table.Column(isNullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerIdentityStrategy.IdentityColumn),
Name = table.Column(isNullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Model", x => x.Id);
});
}
5
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Contacts",
columns: table => new
{
Id = table.Column(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
FirstName = table.Column(nullable: true),
LastName = table.Column(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Contacts", x => x.Id);
});

        migrationBuilder.CreateTable(
            name: "Customers",
            columns: table => new
            {
                Id = table.Column<int>(nullable: false)
                    .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
                CustomerName = table.Column<string>(nullable: true)
            },
            constraints: table =>
            {
                table.PrimaryKey("PK_Customers", x => x.Id);
            });
    }

6
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Issue",
columns: table => new
{
Id = table.Column(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
Created = table.Column(nullable: false),
Name = table.Column(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Issue", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Person",
columns: table => new
{
Id = table.Column(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
IssueId = table.Column(nullable: true),
Name = table.Column(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Person", x => x.Id);
table.ForeignKey(
name: "FK_Person_Issue_IssueId",
column: x => x.IssueId,
principalTable: "Issue",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
}

7
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Teacher",
columns: table => new
{
ID = table.Column(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
Name = table.Column(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Teacher", x => x.ID);
});
migrationBuilder.CreateTable(
name: "Student",
columns: table => new
{
ID = table.Column(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
Name = table.Column(nullable: true),
TeacherID = table.Column(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Student", x => x.ID);
table.ForeignKey(
name: "FK_Student_Teacher_TeacherID",
column: x => x.TeacherID,
principalTable: "Teacher",
principalColumn: "ID",
onDelete: ReferentialAction.Cascade);
});
}

8
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Game",
columns: table => new
{
Id = table.Column(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
Opponent = table.Column(nullable: true),
Order = table.Column(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Game", x => x.Id);
});
migrationBuilder.CreateTable(
name: "StatLine",
columns: table => new
{
Id = table.Column(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
Assists = table.Column(nullable: false),
FGPercentage = table.Column(nullable: false),
FieldGoals = table.Column(nullable: false),
FieldGoalsAttempted = table.Column(nullable: false),
GameNumber = table.Column(nullable: false),
Player = table.Column(nullable: true),
Points = table.Column(nullable: false),
Rebounds = table.Column(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_StatLine", x => x.Id);
});
}

9
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "CalendarEvent",
columns: table => new
{
Id = table.Column(isNullable: false),
Body = table.Column(isNullable: true),
End = table.Column(isNullable: false),
IsAllDay = table.Column(isNullable: true),
Location = table.Column(isNullable: true),
Start = table.Column(isNullable: false),
Subject = table.Column(isNullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_CalendarEvent", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Emails",
columns: table => new
{
Id = table.Column(isNullable: false),
Body = table.Column(isNullable: true),
DateTimeSent = table.Column(isNullable: false),
From = table.Column(isNullable: true),
Subject = table.Column(isNullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Emails", x => x.Id);
});
}

10
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(name: "CorrectedTweets", schema: "mab");
migrationBuilder.CreateTable(
name: "CorrectedTweet",
schema: "mab",
columns: table => new
{
Id = table.Column(nullable: false),
CorrectedOn = table.Column(nullable: false),
ScreenName = table.Column(nullable: true),
StatusId = table.Column(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_CorrectedTweet", x => x.Id);
});
migrationBuilder.CreateTable(
name: "OutgoingTweet",
schema: "mab",
columns: table => new
{
Id = table.Column(nullable: false),
InReplyToScreenName = table.Column(nullable: true),
InReplyToStatusId = table.Column(nullable: false),
Text = table.Column(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_OutgoingTweet", x => x.Id);
});
}

11
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "AnswerData",
columns: table => new
{
Id = table.Column(nullable: false),
AnsweredBy = table.Column(nullable: true),
Content = table.Column(nullable: true),
QuestionId = table.Column(nullable: false),
Votes = table.Column(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AnswerData", x => x.Id);
});
migrationBuilder.CreateTable(
name: "QuestionData",
columns: table => new
{
Id = table.Column(nullable: false),
AskedByUserName = table.Column(nullable: true),
Content = table.Column(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_QuestionData", x => x.Id);
});
}

12

protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Role",
columns: table => new
{
RoleID = table.Column(nullable: false),
Description = table.Column(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Role", x => x.RoleID);
});
migrationBuilder.CreateTable(
name: "User",
columns: table => new
{
UserID = table.Column(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
CustomProperty = table.Column(nullable: true),
Email = table.Column(nullable: true),
Password = table.Column(nullable: false),
RoleID = table.Column(nullable: false),
Username = table.Column(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_User", x => x.UserID);
table.ForeignKey(
name: "FK_User_Role_RoleID",
column: x => x.RoleID,
principalTable: "Role",
principalColumn: "RoleID");
});
}

13

protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Migrations",
columns: table => new
{
Context = table.Column(nullable: false),
Version = table.Column(nullable: false),
Metadata = table.Column(type: "ntext", nullable: false),
Migration = table.Column(type: "ntext", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Migrations", x => new { x.Context, x.Version });
});

        migrationBuilder.CreateTable(
            name: "Snapshots",
            columns: table => new
            {
                Context = table.Column<string>(nullable: false),
                Version = table.Column<string>(nullable: false),
                Snapshot = table.Column<string>(type: "ntext", nullable: false)
            },
            constraints: table =>
            {
                table.PrimaryKey("PK_Snapshots", x => x.Context);
            });
    }

14

protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Level",
columns: table => new
{
Id = table.Column(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
Created = table.Column(nullable: false),
Name = table.Column(nullable: true),
UserName = table.Column(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Level", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Quest",
columns: table => new
{
Id = table.Column(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
DueBy = table.Column(nullable: false),
Name = table.Column(nullable: true),
Reward = table.Column(nullable: true),
Status = table.Column(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Quest", x => x.Id);
});
}

15
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "State",
columns: table => new
{
Id = table.Column(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
Name = table.Column(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_State", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Message",
columns: table => new
{
Id = table.Column(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
StateId = table.Column(nullable: false),
Text = table.Column(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Message", x => x.Id);
table.ForeignKey(
name: "FK_Message_State_StateId",
column: x => x.StateId,
principalTable: "State",
principalColumn: "Id");
});
}

添加列 删除列
//向上迁移,会增加一列
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn(
name: "Height",
table: "T_Persons",
nullable: false,
maxLength: 50,
defaultValue: 0.0);
}

    protected override void Down(MigrationBuilder migrationBuilder)
    {
        //向下迁移就会删除T_Persons表中的Height列
        migrationBuilder.DropColumn(
            name: "Height",
            table: "T_Persons");
    }

删除外键
migrationBuilder.DropForeignKey(
name: "FK_CourseAssignment_Instructor_InstructorID",
table: "CourseAssignment");

删除索引
migrationBuilder.DropIndex(name: "IX_Enrollment_StudentID", table: "Enrollment");

        migrationBuilder.RenameTable(name: "Instructor", newName: "Person");  重命名表
        migrationBuilder.AddColumn<DateTime>(name: "EnrollmentDate", table: "Person", nullable: true); 添加列
        migrationBuilder.AddColumn<string>(name: "Discriminator", table: "Person", nullable: false, maxLength: 128, defaultValue: "Instructor");修改列
        migrationBuilder.AlterColumn<DateTime>(name: "HireDate", table: "Person", nullable: true);
        migrationBuilder.AddColumn<int>(name: "OldId", table: "Person", nullable: true);

migrationBuilder.DropColumn(name: "OldID", table: "Person");

migrationBuilder.Sql(""); 执行sql
添加外键
migrationBuilder.AddForeignKey(
name: "FK_Enrollment_Person_StudentID",
table: "Enrollment",
column: "StudentID",
principalTable: "Person",
principalColumn: "ID",
onDelete: ReferentialAction.Cascade);
添加索引
migrationBuilder.CreateIndex(
name: "IX_Enrollment_StudentID",
table: "Enrollment",
column: "StudentID");
}
主键
table.PrimaryKey("PK_IdentityUserClaim", x => x.Id);
table.PrimaryKey("PK_IdentityUserLogin", x => new { x.LoginProvider, x.ProviderKey });

   默认值
    migrationBuilder.AddColumn<DateTimeOffset>(
            name: "EndDateTime",
            table: "Activity",
            nullable: false,
            defaultValue: new DateTimeOffset(new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), new TimeSpan(0, 0, 0, 0, 0)));
        migrationBuilder.AddColumn<DateTimeOffset>(
            name: "StartDateTime",
            table: "Activity",
            nullable: false,
            defaultValue: new DateTimeOffset(new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), new TimeSpan(0, 0, 0, 0, 0)));

添加列参数
public virtual Microsoft.EntityFrameworkCore.Migrations.Operations.Builders.OperationBuilder<Microsoft.EntityFrameworkCore.Migrations.Operations.AddColumnOperation> AddColumn (string name, string table, string? type = default, bool? unicode = default, int? maxLength = default, bool rowVersion = false, string? schema = default, bool nullable = false, object? defaultValue = default, string? defaultValueSql = default, string? computedColumnSql = default, bool? fixedLength = default, string? comment = default, string? collation = default, int? precision = default, int? scale = default, bool? stored = default);

添加表参数
public virtual Microsoft.EntityFrameworkCore.Migrations.Operations.Builders.CreateTableBuilder CreateTable (string name, Func<Microsoft.EntityFrameworkCore.Migrations.Operations.Builders.ColumnsBuilder,TColumns> columns, string? schema = default, Action<Microsoft.EntityFrameworkCore.Migrations.Operations.Builders.CreateTableBuilder>? constraints = default, string? comment = default);
''''

三 多个dbcontext

dotnet ef migrations add initail -c PermissionDbContext

dotnet ef database update -c PermissionDbContext
如果 DbContext 在另一个 DLL 中时报错:
解决办法:

services.AddDbContext(options =>
options.UseSqlServer(configuration.GetConnectionString("PermissionConnection"), b => b.MigrationsAssembly(assemblyName)));
其中 assemblyName 是主DLL 名称的字符串常量。(不知道为什么,它不能为变量 AppDomain.CurrentDomain.FriendlyName)。

四 更新指定的migration版本
移除迁移(删除最近的一次迁移) dotnet ef migrations remove
应用所有的迁移(使迁移文件应用到数据库) dotnet ef database update
生成对应版本的脚本 dotnet ef migrations script
查看迁移列表 dotnet ef migrations list
查看数据库上下文信息 dotnet ef dbcontext info
dotnet ef migrations add migrationName
dotnet ef database update migrationName

posted @ 2022-08-29 15:17  过错  阅读(1339)  评论(0编辑  收藏  举报