あらかじめこちらで SQL Server へ接続できるユーザーを作成します。
SQL Server へ 「SQL Server認証」でログインするユーザーを作成し .Net アプリのDB接続に使用する|プログラムメモ
.NET Coreでコードファーストを使ってDBを作成するまでは大きく分けて次の手順となります。
・1. csファイルの作成と編集
- モデルクラスの作成
- DBコンテキストの作成
- Startup.cs の ConfigureServices() メソッド内に コンテキスト読込を追加
・2. マイグレーションファイルの生成( dotnet ef migrations add )
・3. マイグレーションの実行( dotnet ef database update )
dotnet コマンドは PowerShell から実行します。(Visual Studioのコンソールではありません。)
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 を使うときに記述します。
(データベースの種類によって書き換えること)
dotnet tool install --global dotnet-ef
dotnet tool install --global dotnet-ef --version 3.0.0
あと Microsoft.EntityFrameworkCore.SqlServer もインストールしておいてください。
dotnet ef migrations add ver1.0
複数コンテキストがある場合はコンテキストを指定する必要があります。
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
dotnet ef database update
dotnet ef database update --context MyContext
データベース全体を Drop します
dotnet ef database drop
dotnet ef database drop -f
複数コンテキストがある場合はコンテキストを指定する必要があります。 (ただしDB全体がdropされるので注意)
dotnet ef database drop --context ApplicationDbContext -f