.NET Core で コードファーストでデータベースを作成する

あらかじめこちらで SQL Server へ接続できるユーザーを作成します。

SQL Server へ 「SQL Server認証」でログインするユーザーを作成し .Net アプリのDB接続に使用する|プログラムメモ

● .NET Core Entity Framework コードファーストの手順

.NET Coreでコードファーストを使ってDBを作成するまでは大きく分けて次の手順となります。

・1. csファイルの作成と編集
    - モデルクラスの作成
    - DBコンテキストの作成
    - Startup.cs の ConfigureServices() メソッド内に コンテキスト読込を追加
・2. マイグレーションファイルの生成( dotnet ef migrations add )
・3. マイグレーションの実行( dotnet ef database update )

dotnet コマンドは PowerShell から実行します。(Visual Studioのコンソールではありません。)

● ・1. csファイルの作成と編集

Models/Memo.cs を以下のように作成

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace 【アプリ名】.Models
{
    public class Memo
    {
        public int ID { get; set; }
        public string Title { get; set; }
    }
}

IDを表すカラム名は必ず大文字で「ID」である必要があります。

Data/MyContext.cs を以下の内容で作成

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using 【アプリ名】.Models;

namespace 【アプリ名】.Data
{
    public class MyContext : DbContext
    {
        public MyContext( DbContextOptions options ) : base( options )
        {

        }
        public DbSet<Memo> Memo { get; set; }
    }
}

Startup.cs に以下の行を追加

using Microsoft.EntityFrameworkCore; を追加

using Microsoft.EntityFrameworkCore;
        public void ConfigureServices(IServiceCollection services)
        {
            // コンテキストクラスを追加ここから
            services.AddDbContext<MyContext>( options => options.UseSqlServer(
                 Configuration.GetConnectionString( "DefaultConnection" )
             ) );
            // コンテキストクラスを追加ここまで

(options.UseSqlServer)は MS SQL Server を使うときに記述します。
(データベースの種類によって書き換えること)

● 2. データベーステーブルのマイグレーションの作成の準備( dotnet-ef のインストール)

dotnet tool install --global dotnet-ef
dotnet tool install --global dotnet-ef --version 3.0.0

あと Microsoft.EntityFrameworkCore.SqlServer もインストールしておいてください。

● 2. データベーステーブルのマイグレーションの作成

dotnet ef migrations add ver1.0

● 2. (コンテキストを指定した)データベーステーブルのマイグレーションの作成

複数コンテキストがある場合はコンテキストを指定する必要があります。

dotnet ef migrations add __My__Ver1.2__  --context MyContex

このとき Migrations ディレクトリ内に次のようなファイルが生成されます。

20180704061421___My__Ver1.2__.cs
20180704061421___My__Ver1.2__.Designer.cs
dotnet ef migrations add __ApplicationDb__Ver1.2__  --context ApplicationDbContext

● 3. データベーステーブルのマイグレーションの実行

dotnet ef database update

● 3. (コンテキストを指定した)データベーステーブルのマイグレーションの実行

dotnet ef database update --context MyContext

● データベースの削除

データベース全体を Drop します

dotnet ef database drop

● データベースの削除(削除確認なし)

dotnet ef database drop -f

● データベースの削除( ApplicationDbContext を使って削除 )

複数コンテキストがある場合はコンテキストを指定する必要があります。 (ただしDB全体がdropされるので注意)

dotnet ef database drop --context ApplicationDbContext -f

関連エントリー

No.1266
06/10 16:45

edit

EntityFrameworkCore