2017-02-28 5 views
1

私は現在、移行を使用する.NETコアのIdentity Serverアプリケーションを構築しており、データベースをシードするための最良の方法が.NETコアに関してどのようになるのか疑問に思っています。.NETコアにシードする

現在、私は起動時に呼び出されるDbInitializerクラスを持っていますが(以下を参照)、これを移行として実行する必要があるかどうか疑問に思っていますか?

public static void Seed(IApplicationBuilder applicationBuilder) 
    { 
     ConfigurationDbContext context = 
      applicationBuilder.ApplicationServices.GetRequiredService<ConfigurationDbContext>(); 
     IConfiguration oConfig = 
      applicationBuilder.ApplicationServices.GetRequiredService<IConfiguration>(); 

     string sSeedingConfig = GetSeedingConfiguration(oConfig); 

     SeedConfigurationDb(ref context, sSeedingConfig); 
    } 

    private static void SeedConfigurationDb(ref ConfigurationDbContext oContext, string sSeedingConfig) 
    { 
     if (!oContext.ApiResources.Any()) 
     { 
      var oApis = GetSeedingConfigElements(sSeedingConfig, "Apis"); 
      List<ApiResource> lApis = null; 
      if (oApis != null) 
      { 
       lApis = JsonConvert.DeserializeObject<List<ApiResource>>(oApis.ToString()); 
      } 
      if (lApis != null) 
      { 
       foreach (var api in lApis) 
       { 
        oContext.ApiResources.Add(api.ToEntity()); 
       } 
      } 
     } 

     if (!oContext.Clients.Any()) 
     { 
      var oClients = GetSeedingConfigElements(sSeedingConfig, "Clients"); 
      List<Client> lClients = null; 
      if (oClients != null) 
      { 
       lClients = JsonConvert.DeserializeObject<List<Client>>(oClients.ToString()); 
      } 
      if (lClients != null) 
      { 
       foreach (var client in lClients) 
       { 
        oContext.Clients.Add(client.ToEntity()); 
       } 
      } 
     } 

     if (!oContext.IdentityResources.Any()) 
     { 
      var oIdentityResources = GetSeedingConfigElements(sSeedingConfig, "IdentityResources"); 
      List<IdentityResource> lIdentityResources = null; 
      if (oIdentityResources != null) 
      { 
       lIdentityResources = JsonConvert.DeserializeObject<List<IdentityResource>>(oIdentityResources.ToString()); 
      } 
      if (lIdentityResources != null) 
      { 
       foreach (var identityresource in lIdentityResources) 
       { 
        oContext.IdentityResources.Add(identityresource.ToEntity()); 
       } 
      } 
     } 

     oContext.SaveChanges(); 
    } 

答えて

4

移行を有効にすると、「構成」という名前のクラスファイルが取得されます。このクラスには、移行を通じてデータベースを更新するたびに実行されるシードメソッドがあります。

最初の更新トラフをシードしてからコメントアウトすることができます。

+0

私は実際に次のコマンドを実行して、データベースを作成しました。 'dotnet ef migrations add InitialIdentityServerMigration -c ConfigurationDbContext'。このメソッドはデフォルトでコンフィグレーションクラスを構築しなかったので、実装が新しいフレームワークと若干異なるかどうかはわかりませんでした。以前のフレームワークのバージョンでは、これは常にシーディングプロセスを実行する方法でしたが、.NETコアは慣れていくのに時間がかかりました。 – GSkidmore

+1

@GSkidmoreこれをチェックしてください:http://www.dalsoft.co.uk/blog/index.php/2016/12/13/entity-framework-core-seeding-using-migrations/、それは種まきEFコアで機能が追加されるまでは、移行が必要です。 – TanguyB

+0

華麗なありがとう、本当に感謝します! – GSkidmore

関連する問題