但是我们不要急于写入数据,现在还没有数据库。一切已经准备就绪,我们只需要通过几行命令就可以轻松创建数据库。
在 vs
的控制台直接执行命令是最简单的方式,依次执行:
PM> add-migration InitialIdentityServerPersistedGrantDbMigrationMysql -c PersistedGrantDbContext -o MigrationsMySql/PersistedGrantDb
Build started...
Build succeeded.
To undo this action, use Remove-Migration.
PM> update-database -context PersistedGrantDbContext
Build started...
Build succeeded.
Done.
PM> add-migration InitialIdentityServerConfigurationDbMigrationMysql -c ConfigurationDbContext -o MigrationsMySql/ConfigurationDb
Build started...
Build succeeded.
To undo this action, use Remove-Migration.
PM> update-database -context ConfigurationDbContext
Build started...
Build succeeded.
Done.
PM> add-migration AppDbMigration -c ApplicationDbContext -o MigrationsMySql
Build started...
Build succeeded.
To undo this action, use Remove-Migration.
PM> update-database -context ApplicationDbContext
Build started...
Build succeeded.
Done.
因为可能版本不一致,旧版的 update-database
的 -c
是没有问题的,但新版由于新增了参数,会报冲突,使用全称即可。
下同,但全称是 --context
。
也可以通过 dotnet
命令执行,需要先安装 Entity Framework Core CLI,并在项目中安装 Microsoft.EntityFrameworkCore.Design
:
dotnet tool install --global dotnet-ef
dotnet add package Microsoft.EntityFrameworkCore.Design
然后依次执行下面命令:
dotnet ef migrations add InitialIdentityServerPersistedGrantDbMigrationMysql -c PersistedGrantDbContext -o MigrationsMySql/PersistedGrantDb
dotnet ef database update -c PersistedGrantDbContext
dotnet ef migrations add InitialIdentityServerConfigurationDbMigrationMysql -c ConfigurationDbContext -o MigrationsMySql/ConfigurationDb
dotnet ef database update -c ConfigurationDbContext
dotnet ef migrations add AppDbMigration -c ApplicationDbContext -o MigrationsMySql
dotnet ef database update -c ApplicationDbContext
运行之后,可以看到在项目中多了一个 MigrationsMySql
的文件夹,里面有很多自动生成的文件:
同时,在数据库中可以看到已经生成了对应的表:
生成的文件为模型文件,如果没有修改我们的自定义实体模型,可以一直使用,只需要执行 update 命令即可创建数据库。如果修改了模型结构,将整个文件夹删掉重新生成,并执行全部命令即可。