安装迁移工具需要的插件
- Microsoft.EntityFrameworkCore.Tools
- Microsoft.EntityFrameworkCore.Design
补充说明:
安装在Demo.Data项目下,很显然这里需要迁移的是DbContext,与此同时,安装了Microsoft.EntityFrameworkCore,Tools就会依赖另一个,所以无需安装另一个。
迁移命令
- 搜索框输入:Package Manager Console
- Default Project选择Demo.Data
- 键入:get-help entityFramework 出现独角兽
- 开始迁移,即将三个model嵌入到数据库中:Add-Migration Initial
- 需要对Demo.App安装Microsoft.EntityFrameworkCore.Design
- 再次使用add-migration Initial
- 清空指令 clear
- 生成数据库的脚本Script-Migration
```sql
IF OBJECT_ID(N’[EFMigrationsHistory]’) IS NULL
BEGIN
CREATE TABLE [EFMigrationsHistory] (
); END;[MigrationId] nvarchar(150) NOT NULL,
[ProductVersion] nvarchar(32) NOT NULL,
CONSTRAINT [PK___EFMigrationsHistory] PRIMARY KEY ([MigrationId])
GO
CREATE TABLE [Leagues] ( [Id] int NOT NULL IDENTITY, [Name] nvarchar(max) NULL, [Country] nvarchar(max) NULL, CONSTRAINT [PK_Leagues] PRIMARY KEY ([Id]) );
GO
CREATE TABLE [Clubs] ( [Id] int NOT NULL IDENTITY, [Name] nvarchar(max) NULL, [City] nvarchar(max) NULL, [DateOfEstablishment] datetime2 NOT NULL, [History] nvarchar(max) NULL, [LeagueId] int NULL, CONSTRAINT [PK_Clubs] PRIMARY KEY ([Id]), CONSTRAINT [FK_Clubs_Leagues_LeagueId] FOREIGN KEY ([LeagueId]) REFERENCES [Leagues] ([Id]) ON DELETE NO ACTION );
GO
CREATE TABLE [Players] ( [Id] int NOT NULL IDENTITY, [Name] nvarchar(max) NULL, [DateOfBirth] datetime2 NOT NULL, [ClubId] int NULL, CONSTRAINT [PK_Players] PRIMARY KEY ([Id]), CONSTRAINT [FK_Players_Clubs_ClubId] FOREIGN KEY ([ClubId]) REFERENCES [Clubs] ([Id]) ON DELETE NO ACTION );
GO
CREATE INDEX [IX_Clubs_LeagueId] ON [Clubs] ([LeagueId]);
GO
CREATE INDEX [IX_Players_ClubId] ON [Players] ([ClubId]);
GO
INSERT INTO [__EFMigrationsHistory] ([MigrationId], [ProductVersion]) VALUES (N’20200828130407_Initial’, N’3.1.7’);
GO
```
- 开发环境我们使用Update-Database -verbose(生成log明细)
- 这里提一个概念,反向工程,即数据已经存在表了