1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

EFcoreのマイグレーションでテーブルの存在確認をする_C#

1
Last updated at Posted at 2024-09-24

すでに作成して使用しているアプリに、後からEntityFramework_coreを使うように置き換えようとしています。
データモデルを作り、マイグレーションしてみますが、すでにテーブルが存在するとCreateTableでエラーになります。
その時に、テーブルの存在確認をする方法についてです。

前提として

コードファーストでマイグレーションしようとしているのに、テーブルの存在確認をして対応する。ということをすると問題の起きる懸念があります。
Issuesにいくつかありました。
https://github.com/dotnet/efcore/issues/13703
https://github.com/dotnet/efcore/issues/32071

テーブルの存在確認をしない方法

migrationBuilder.CreateTableの処理を以下に変えて対応するという方法もあるようです。
https://sqlite.org/lang_altertable.html#otheralter

  1. 新しいテーブルを作成する
  2. データのコピー
  3. 古いテーブルの削除
  4. 新しい名前を古い名前に変更

テーブルの存在確認をしてからmigrationBuilder.CreateTableする

使用環境

  • windows10
  • .net net8.0-windows
  • winフォーム
  • SQLite
  • 使用するPCのローカルにSQLiteファイルを作成
  • すでにアプリは使用されている
  • EFcoreに置き換えて以降はこれでデータベースSQLiteの変更を管理したい
  • 問題として
    • すでにアプリを使用していてSQLiteファイルがある場合は、変更のみを適用したい
    • 初めて使用する場合は、すべてのマイグレーションファイルを適用させたい

マイグレーションファイルの変更

生成されたマイグレーションファイルの内容を変更していきます。

20240802010101_InitialCreate.cs
public partial class InitialCreate : Migration
{
    /// <inheritdoc />
    protected override void Up(MigrationBuilder migrationBuilder)
    {
        if (ContextExtensions.TableExistsCount("myTable") == 0)
        {
            migrationBuilder.CreateTable(
               name: "myTable",
               columns: table => new
               {
                   myCol = table.Column<string>(type: "TEXT", nullable: false)
               },
               constraints: table =>
               {
                   table.PrimaryKey("PK_t_Files", x => x.myCol);
               });
        }
    }
}
public static class ContextExtensions
{
    public static int TableExistsCount(string tableName)
    {
        using MyContext context = new();
        var sSQL = $@"SELECT COUNT(*) as 'Value' FROM sqlite_master WHERE TYPE = 'table' AND name = '{tableName}'";
        var sSQLFactory = FormattableStringFactory.Create(sSQL);
        var tableCount = context.Database.SqlQuery<int>(sSQLFactory).FirstOrDefault();
        return tableCount;
    }
}

変更した内容

  • TableExistsCountという関数を追加
  • if (ContextExtensions.TableExistsCount("myTable") == 0)の所で呼び出す
  • テーブルが存在しない場合にmigrationBuilder.CreateTableの処理をする
  • migrationBuilder.CreateTableの部分はマイグレーションでつくられたファイルのまま

つまった所

EFcoreへの移行ができた

これを使うことで、すでに使用しているアプリの状態から、EFcoreへの管理に移行できました。
これで今後データベースへの変更がある時はマイグレーションファイルを作ってそれぞれの実行環境から更新するだけになりました!
ただ前提の部分のとおり、この方法は推奨される方法ではないと思われます。

その他参考

1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?