見出し画像

93. Entity Framework の Migration 機能を SQL Server で試す

前回の記事

はじめに

今回は、前々回の記事で作成した Entity Framework を使った SQL Server Express 上のデータベースに対して、Entity Framework の Migration 機能を試してみることにします。


準備

まず、SQL Server Express のデータベースを作成した Visual Studio 2022 のプロジェクトをフォルダーごとコピーして最初の状態を保存しておきます。
※ おいおい、git 使えよ…って声が聞こえてきそう(笑)ですが、はい、実システム開発ではそうしてくださいね。Check-in して Branch 作って作業する、これが正解でしょうね。しかし、まぁ、ちょっと試すだけだし、めんどくさいので多めにみてください(苦笑)

最初のトライ(失敗)

何はともあれ、SQLite で試した Entity Framework の Migration 作業をそのままやってみることにします。参考にするのは、前と同様、
移行の概要 - EF Core | Microsoft Learn
です。InitialCreate の Migration を作成してデータベースをアップデートする、そういう作業です。

PM> cd .\WpfAppEFSQLServer
PM> Add-Migration InitialCreate
Build started...
Build succeeded.
Your startup project 'WpfAppEFSQLServer' 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.

ということで、NuGet パッケージのインストールを忘れていたので、Microsoft.EntityFrameworkCore.Design という NuGet パッケージをこのプロジェクトにインストールして、再度実行します。

PM> Add-Migration InitialCreate
Build started...
Build succeeded.
To undo this action, use Remove-Migration.

今回は成功しました。次に、Update-Database を実行してみます。

PM> Update-Database
Build started...
Build succeeded.
Applying migration '20240502235539_InitialCreate'.
Failed executing DbCommand (28ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
CREATE TABLE [Categories] (
    [CategoryId] int NOT NULL IDENTITY,
    [Name] nvarchar(max) NOT NULL,
    CONSTRAINT [PK_Categories] PRIMARY KEY ([CategoryId])
);
Microsoft.Data.SqlClient.SqlException (0x80131904): データベースに 'Categories' という名前のオブジェクトが既に存在します。
   at Microsoft.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at Microsoft.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at Microsoft.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
   at Microsoft.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
   at Microsoft.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean isAsync, Int32 timeout, Boolean asyncWrite)
   at Microsoft.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, Boolean sendToPipe, Int32 timeout, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry, String methodName)
   at Microsoft.Data.SqlClient.SqlCommand.ExecuteNonQuery()
   at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteNonQuery(RelationalCommandParameterObject parameterObject)
   at Microsoft.EntityFrameworkCore.Migrations.MigrationCommand.ExecuteNonQuery(IRelationalConnection connection, IReadOnlyDictionary`2 parameterValues)
   at Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationCommandExecutor.ExecuteNonQuery(IEnumerable`1 migrationCommands, IRelationalConnection connection)
   at Microsoft.EntityFrameworkCore.Migrations.Internal.Migrator.Migrate(String targetMigration)
   at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.UpdateDatabase(String targetMigration, String connectionString, String contextType)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.UpdateDatabaseImpl(String targetMigration, String connectionString, String contextType)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.UpdateDatabase.<>c__DisplayClass0_0.<.ctor>b__0()
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
ClientConnectionId:ce13dfbd-6d61-4e87-9a17-5ff1555e5c8e
Error Number:2714,State:6,Class:16
データベースに 'Categories' という名前のオブジェクトが既に存在します。

SQLite を使って、プロジェクトのフォルダー直下に Products.db を置き、そのデータベースファイルを使ってスキーマを Entity Framework の機能を使って Reverse Engineering したプロジェクトの時と同じエラーが発生しました。前回は脳内思考停止状態でそのまま別のプロジェクトで作業を進めましたが、今回は、ちょっと頭を使ってみることにします。

ここから先は

8,294字 / 5画像

2022年3月にマイクロソフトの中の人から外の人になった Embedded D. George が、現時点で持っている知識に加えて、頻繁に…

この記事が気に入ったらサポートをしてみませんか?