一、前言
數據遷移可使用“包管理器控制台”(PMC) 或 CLI。本文列出使用CLI數據遷移命令和一些問題及解決方案。
二、遷移命令
以下列出添加遷移文件、撤銷遷移、更新到數據庫、刪除數據庫基本方法。如需指定DbContext,則在語句后加 -c DbContext名 。如需查看幫助可在命令后加 -h 。
1、創建遷移文件,遷移文件名必填
dotnet ef migrations add 遷移文件名
2、撤銷遷移,只能在未更新數據庫前撤銷
dotnet ef migrations remove
3、更新到數據庫
dotnet ef database update
4、刪除數據庫
注意不是刪除數據更改,是刪除數據庫,慎用。
dotnet ef database drop
三、問題與解決
1、問題
無法執行,因為找不到指定的命令或文件。
可能的原因包括:
*你拼錯了內置的 dotnet 命令。
*你打算執行 .NET Core 程序,但 dotnet-install 不存在。
*你打算運行全局工具,但在路徑上找不到名稱前綴為 dotnet 的可執行文件。
解決:打開CMD,輸入:
dotnet tool install -g dotnet-ef
2、問題
The EF Core tools version '3.1.0' is older than that of the runtime '3.1.2'. Update the tools for the latest features and bug fixes.
解決:需要更新EF Core tools版本,CMD中執行:
dotnet tool update -g dotnet-ef
3、問題
It was not possible to find any compatible framework version
The framework 'Microsoft.NETCore.App', version '3.1.2' was not found.
- The following frameworks were found:
2.1.9 at [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
2.1.15 at [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
3.1.1 at [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
You can resolve the problem by installing the specified framework and/or SDK.
The specified framework can be found at:
- https://aka.ms/dotnet-core-applaunch?framework=Microsoft.NETCore.App&framework_version=3.1.2&arch=x64&rid=win10-x64
解決:到最后提供的網址下載SDK安裝
4、問題
No database provider has been configured for this DbContext. A provider can be configured by overriding the DbContext.OnConfiguring method or by using AddDbContext on the application service provider. If AddDbContext is used, then also ensure that your DbContext type accepts a DbContextOptions<TContext> object in its constructor and passes it to the base constructor for DbContext.
解決:需要在網站目錄執行
5、問題
More than one DbContext was found. Specify which one to use. Use the '-Context' parameter for PowerShell commands and the '--context' parameter for dotnet commands.
解決:如果有多個DBContext,需要指定遷移哪個DBContext。如:
dotnet ef migrations add InitialCreate -c DBContext名稱
6、問題
Your target project 'Do.TmsApi' doesn't match your migrations assembly 'Do.Models'. Either change your target project or change your migrations assembly.
Change your migrations assembly by using DbContextOptionsBuilder. E.g. options.UseSqlServer(connection, b => b.MigrationsAssembly("Do.TmsApi")). By default, the migrations assembly is the assembly containing the DbContext.
Change your target project to the migrations project by using the Package Manager Console's Default project drop-down list, or by executing "dotnet ef" from the directory containing the migrations project.
解決:如果DBContext和啟動程序不在一個程序集,需要指定要遷移的程序集。代碼中添加要遷移的程序集名稱:
options.UseSqlServer(connection, b => b.MigrationsAssembly("Do.TmsApi"))