layout: docs-default
Schema 修改和遷移
隨著IdentityServer3的一步步改進,數據庫schema可能會改變青团。考慮到這些schema的改變津函,托管程序需要來處理schema改變张抄。
EF提供了migrations (more info here 和here) 來修改schema和數據庫的改變。
DbContexts
這有三種不同的 DbContext
-派生類在EF實現(xiàn)中:
ClientConfigurationDbContext
ScopeConfigurationDbContext
OperationalDbContext
這些數據庫上下文類放在不同的assembly里面(如:IdentityServer3.EntityFramework
) 而不是托管程序碑定。
啟用migrations
每個數據庫上下文都需要創(chuàng)建遷移文件流码,要啟用所有數據庫上下文的遷移,需要在包管理控制臺執(zhí)行下面的命令:
Enable-Migrations -MigrationsDirectory Migrations\ClientConfiguration -ContextTypeName ClientConfigurationDbContext -ContextAssemblyName IdentityServer3.EntityFramework -ConnectionStringName IdSvr3Config
Enable-Migrations -MigrationsDirectory Migrations\ScopeConfiguration -ContextTypeName ScopeConfigurationDbContext -ContextAssemblyName IdentityServer3.EntityFramework -ConnectionStringName IdSvr3Config
Enable-Migrations -MigrationsDirectory Migrations\OperationalConfiguration -ContextTypeName OperationalDbContext -ContextAssemblyName IdentityServer3.EntityFramework -ConnectionStringName IdSvr3Config
初始化架構必須定義延刘,用真實的項目根命名空間替換$ProjectRootNamespace$
然后創(chuàng)建初始化的schema遷移如下:
Add-Migration -Name InitialCreate -ConfigurationTypeName $ProjectRootNamespace$.Migrations.ScopeConfiguration.Configuration -ConnectionStringName IdSvr3Config
Add-Migration -Name InitialCreate -ConfigurationTypeName $ProjectRootNamespace$.Migrations.ClientConfiguration.Configuration -ConnectionStringName IdSvr3Config
Add-Migration -Name InitialCreate -ConfigurationTypeName $ProjectRootNamespace$.Migrations.OperationalConfiguration.Configuration -ConnectionStringName IdSvr3Config
現(xiàn)在可以創(chuàng)建數據庫啦漫试,同樣的$ProjectRootNamespace$
需要替換成根命名空間:
Update-Database -ConfigurationTypeName $ProjectRootNamespace$.Migrations.ClientConfiguration.Configuration -ConnectionStringName IdSvr3Config
Update-Database -ConfigurationTypeName $ProjectRootNamespace$.Migrations.ScopeConfiguration.Configuration -ConnectionStringName IdSvr3Config
Update-Database -ConfigurationTypeName $ProjectRootNamespace$.Migrations.OperationalConfiguration.Configuration -ConnectionStringName IdSvr3Config
一旦應用更新到新的版本,可以使用Add-Migration
和Update-Database
來更新架構碘赖,請檢查 EF 文檔 了解更多.
提供標準的作用域
我們可以使用來自ScopeConfiguration/Configuration.cs種子(Seed)方法來創(chuàng)建標準的作用域驾荣。
protected override void Seed(IdentityServer3.EntityFramework.ScopeConfigurationDbContext context)
{
//Providing standard scopes
foreach (var standardScope in StandardScopes.All)
{
if (!context.Scopes.Any(s => s.Name == standardScope.Name))
context.Scopes.Add(standardScope.ToEntity());
}
if (!context.Scopes.Any(s => s.Name == StandardScopes.Roles.Name))
context.Scopes.Add(StandardScopes.Roles.ToEntity());
if (!context.Scopes.Any(s => s.Name == StandardScopes.OfflineAccess.Name))
context.Scopes.Add(StandardScopes.OfflineAccess.ToEntity());
}