2016-08-24 60 views
4

根據構建配置(調試/發佈),使用實體框架(6+)對種子數據庫進行不同種子的建議方法是什麼?用於開發和生產的不同種子

現在我正在使用MigrateDatabaseToLatestVersion初始化程序。在開發過程中,我喜歡在數據庫中僞造數據以進行測試。所以我在配置類的Seed方法中創建了這個測試數據(隨代碼優先啓用)。但是,每次我通過構建服務器發佈產品時,我都必須在我的種子方法中評論很多代碼,執行此操作,創建發行版,然後撤消所有註釋以繼續使用測試數據進行開發。

我想這不是要走的路。所以我希望你能告訴我這樣做的正確方法。

+1

你就不能使用'#如果DEBUG'預處理指令?否則引入你自己的構建配置。 –

+0

我在想那個。但是,我不確定這是否是要走的路。如果有什麼我從來沒有見過的,我經常開始認爲我可能是錯的。 – Sam

+1

這就是我要做的,當然! –

回答

5

有很多可能性

  1. 預處理指令

一個是像你和格特·阿諾德已經談到,使用#if DEBUG

protected override void Seed(BookService.Models.BookServiceContext context) 
{ 
#if DEBUG 
    context.Authors.AddOrUpdate(x => x.Id, 
     new Author() { Id = 1, Name = "Test User" }, 
    ); 
#else 
    context.Authors.AddOrUpdate(x => x.Id, 
     new Author() { Id = 1, Name = "Productive User" }, 
    ); 
#endif 
} 
  • 配置
  • 另一種方法是使用配置在appsettings.json,也許你想建立與發展,數據的應用程序,你可以添加類似

    { "environment" : "development" } 
    

    ,並在種子,你檢查這一點:

    protected override void Seed(BookService.Models.BookServiceContext context) 
    { 
        var builder = new ConfigurationBuilder(); 
        builder.AddInMemoryCollection(); 
        var config = builder.Build(); 
    
        if (config["environment"].Equals("development")) 
        { 
         context.Authors.AddOrUpdate(x => x.Id, 
          new Author() { Id = 1, Name = "Test User" }, 
         ); 
        } 
        else if (config["environment"].Equals("producion")) 
        { 
         context.Authors.AddOrUpdate(x => x.Id, 
          new Author() { Id = 1, Name = "Productive User" }, 
         ); 
        } 
    } 
    
  • 環境變量(溶液ASP網絡核心
  • (見https://docs.asp.net/en/latest/fundamentals/environments.html

    您可以通過DI加一個環境變量

    enter image description here 後來就:

    public void Configure(IApplicationBuilder app, IHostingEnvironment env) 
    { 
        if (env.IsDevelopment()) 
        { 
         SeedDataForDevelopment(); 
        } 
    } 
    
    +2

    這很棒! –

    相關問題