LoginSignup
2
4

More than 3 years have passed since last update.

EF Core でマイグレーションを実行する際に発生しうるエラーとその対処法

Posted at

EF Core でマイグレーションを実行する際、各種実装後にパッケージマネージャーコンソールで以下のコマンドを実行します。

Add-Migration InitialCreate

コマンド実行時に色々エラーが出てハマったので、本記事では出たエラーと対処法についてそれぞれまとめます。

Build failed.

ソリューションのビルドに失敗すると起きる事象です。
解決方法としては、ソリューションのビルドが成功するように修正してください。

No DbContext was found in assembly 'プロジェクト名'.

エラー文の詳細は下記です。

No DbContext was found in assembly 'プロジェクト名'. Ensure that you're using the correct assembly and that the type is neither abstract nor generic.

DBContext を定義していないプロジェクトでマイグレーションコマンドを実行しようとすると起きる事象です。
解決方法としては、DBContext を定義しているプロジェクトでマイグレーションコマンドを実行するようにしてください。

Your startup project 'プロジェクト名' doesn't reference Microsoft.EntityFrameworkCore.Design.

エラー文の詳細は下記です。

Your startup project 'プロジェクト名' doesn't reference Microsoft.EntityFrameworkCore.Design. This package is required for the Entity Framework Core Tools to work. Ensure your startup project is correct, install the package, and try again.

Microsoft.EntityFrameworkCore.Design がインストールされていないと起きる事象です。
解決方法としては、NuGet パッケージマネージャーで Microsoft.EntityFrameworkCore.Tools をインストールしてください。
Tools の中に Design も含まれています。

Startup project 'プロジェクト名' targets framework '.NETStandard'.

エラー文の詳細は下記です。

Startup project 'プロジェクト名' targets framework '.NETStandard'. There is no runtime associated with this framework, and projects targeting it cannot be executed directly. To use the Entity Framework Core Package Manager Console Tools with this project, add an executable project targeting .NET Framework or .NET Core that references this project, and set it as the startup project; or, update this project to cross-target .NET Framework or .NET Core. For more information on using the EF Core Tools with .NET Standard projects, see https://go.microsoft.com/fwlink/?linkid=2034705

csproj ファイルの TargetFramework が.NET Framework もしくは.NET Core になっていないと起きる事象です。
解決方法としては、.NET Framework もしくは.NET Core に設定されているか見直しましょう。

<TargetFramework>netcoreapp3.1</TargetFramework>

まとめ

EF Core のマイグレーションはコマンドを実行するだけで簡単に実現できるので便利ですが、結構ハマりどころもあります。

他にも以下のサイトで事例が紹介されていましたので、参照してみてください。

.NET Core で DB マイグレーションを試したら色々ハマった話 - ecbeing labs(イーシービーイング・ラボ)

2
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
4