環境
EntityFrameworkCoreのインストール
NugetからMicrosoft.EntityFrameworkCoreをインストールする.

使用するDBに応じてパッケージをインストールする
今回はSQLServerを使うので,Microsoft.EntityFrameworkCore.SqlServerをインストールする.

Identityのインストール
NugetからMicrosoft.AspNetCore.Identity.EntityFrameworkCoreをインストールする.

IdentityDbContextクラスを継承したクラスを作成する
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { }
すでにEntityFrameworkを使用している場合はDbContextを継承したクラスがあるので,親クラスをDbContextからIdentityDbContextに変更するだけでよい.
IdentityDbContextクラスはDbContextクラスを継承している.
サービスを追加する
Startup.cs内のConfigureServicesメソッド内で,Identityを使用するためのサービスを追加する.
public void ConfigureServices(IServiceCollection services) { string connectionString = Configuration.GetConnectionString("OAuthDbConnection"); services.AddDbContextPool<AppDbContext>(options => options.UseSqlServer(connectionString)); services.AddRazorPages(); //これ. services.AddIdentity<IdentityUser, IdentityRole>() .AddEntityFrameworkStores<AppDbContext>(); }
appsettings.jsonはこんなかんじ.GetConnectionStringsメソッドでここに記述した接続文字列を取得している。 この例はローカルのSqlServerExpressを使うようにしている。
"ConnectionStrings": { "OAuthDbConnection": "Server=.\\SQLEXPRESS;Database=OAuthDB;Trusted_Connection=True;" }
Identityで使用するユーザーやロールなどの情報をEntityFrameworkを使って作成,操作するので,AddEntityFrameworkStoresをつなげている.
ミドルウェアを追加する
Configureメソッドに認証ミドルウェアを追加する.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { //省略 app.UseAuthentication();//これ //省略 }
EntityFrameworkCore.Designをインストール
これはマイグレーションを行うために必要.

EntityFrameworkCore.Toolsをインストール
これはAdd-MigrationなどのコマンドをPackage Manager Consoleで使えるようにするために必要.

Migration
Add-Migrationを実行する.
Update-Databaseを実行する.
これでDBにIdentity関連のいくつかのテーブルが作成される.
EFCoreの手順を書くのは何度目だろう....