LoginSignup
0
0

More than 3 years have passed since last update.

ASP.NET COREのデータの再定義を行う(macOS)

Posted at

概要

また詰まりました。
今度は「一度MySQLにマイグレーションしたデータベースを中身のデータを消さずにデータの再定義を行う」です。

一言で言えばRuby on Railsでいう、
rails g migration

マイグレーションファイルに記述(カラム追加、変更、テーブル追加など)

rails db:migrate
の様な流れでモデル操作をしたかったのですが、なかなかうまく行きませんでした。
Windows環境なら簡単そうなのですが、、、

一度データベース(MySQL)に接続した場合、
dotnet ef migrations remove -f

モデル.cs編集

dotnet ef migrations add データベース名

dotnet ef database update
をすればデータベース再定義できるのですが、データベースの中身が全て破棄されてしまいます。
これは困る。
というので今回もmacOSで作業を行っていきます。

作業

モデル編集

今回は「既存のテーブルにカラムを追加する」ことを想定して作業します。
なのでモデルを編集します。

モデル.cs

public class モデル
{
  〜中略〜
  [Timestamp]
  public byte[] RowVersion { get; set; }
}

dotnet efコマンドで新しいマイグレーションファイルを作成する

必ずプロジェクトをビルドしてから、コマンドで新しいマイグレーションファイルを作成します。
このビルドをせずに作業してしまったので、先に進まず苦労しました。

$ dotnet ef migrations add AddRowVersionToモデル

そうすると出来上がったマイグレーションファイルはこの様に自動生成されています。

マイグレーションファイル
using System;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;

namespace アプリ名.Migrations
{
    public partial class AddRowVersionToモデル名 : Migration
    {
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.AddColumn<DateTime>(
                name: "RowVersion",
                table: "テーブル名",
                rowVersion: true,
                nullable: true)
                .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.ComputedColumn);
        }

        protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.DropColumn(
                name: "RowVersion",
                table: "テーブル名");
        }
    }
}

dotnet efコマンドでデータベースにマイグレートする

$ dotnet ef database update

これで完了です

追記

dotnet efコマンドでエラーが起きた際、
原因を知りたい時には -vを末尾につけると良いです。
今回調べて役立ちました。

ex.

$ dotnet ef migrations add AddRowVersionToモデル -v

ご覧いただきありがとうございました。

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