使用 dotnet-ef 进行数据库迁移
使用CI CD进行项目发布时,我们通常需要 dotnet-ef 来更新数据库。 开发的时候我们更常用的是PMC
安装 dotnet-ef
shell
dotnet tool install --global dotnet-ef添加特定版本的
dotnet tool install --global dotnet-ef --version 6.*
dotnet tool install --global dotnet-ef --version 5.*跟据提示我们可能还需要设置环变量
setx PATH "%PATH%;C:\Users\malema\.dotnet\tools"(新设置的环变量对当前的应用程序是无效的。需要新开一个命令行窗口)
添加一个新的migration
shell
dotnet ef migrations add name删除最近的migration
shell
dotnet ef migrations remove如果这个Migration已被应用到数据库就需要使用 dotnet ef database update <上一个migrationName> 先去掉它
更新数据库
更新数据库到最近的版本
shell
dotnet ef database update更新数据库到某个版本, 用于回滚
shell
dotnet ef database update <migrationName>如遇使用了CD进行部署的话需要先配置一下数据库字符串 在linux环境下用下面的代码
shell
export dbconnection='Data Source=127.0.0.1;Initial Catalog=MalemaEFCoreMigration;Persist Security Info=True;User Id=sa;Password=malema987^^%$'生成数据库更新脚本
dotnet ef migrations script有两个默认的参数 <From> <To> 通常我们可能需要写一个from就行了。默认的情况下是从第一个开始的。如果我们有很多的Migration的历史记录, 在 CI当中我们可以定期的指定一下这个参数。这样它不会生成非常多的更新脚本。
dotnet ef migrations script xxxMigrationName--idempotent 幂等性
shell
dotnet ef migrations script --idempotent会生所有的Migration的脚本, 并且每一个变更之前会先判断该变更是不是已经存在了。 比如新建一张表,会先判断这张表是不是已经存在于数据库。
--output 生成的文件的路径
在 Azure piplelines 当中我们需要把这个文件扔到Artifact当中 我们可以写如下的代码
shell
--output $(Build.ArtifactStagingDirectory)/migrations/scripts.sql$(Build.ArtifactStagingDirectory) 这个是auzure pipleline获取 Artifact临时路径
--project 指定项目路径
shell
dotnet ef database update --project ./src/dbmigation/dbmigration.csproj如果没有使用这个参数的话。则默认查找当前目录下的项目文件。
出错
error 1. 无法执行,因为找不到指定的命令或文件。 可能的原因包括: *内置的 dotnet 命令拼写错误。 *你打算执行 .NET 程序,但 dotnet-ef 不存在。
因为我们之前没有设置环境变量。 这个时候我们需要把执行 下面的命令把它卸载掉
shell
dotnet tool uninstall --global dotnet-eferror 2. To install missing framework, download: 在 azure 的 devops 上面碰到了这个问题。 项目是.net 5 但是 ci cd 的服务器 是 Ubuntu 22.04 它是没有自带.net5运行环境。 并且不能简单用 apt-get 来安装 .net 5 只能把服务器切回到 Ubuntu 20.04.
