2012-11-20 35 views
4

如何使EF遷移無需在所需的無參數構造函數的基礎上硬編碼nameorconnectionstring?如何在不使用硬編碼的情況下使用EF CodeFirst Migrations nameOrConnectionString

EF遷移迫使您將默認構造函數添加到自定義dbcontext。在dbcontext的基礎中,你必須提供一個名稱或連接字符串。

public class CustomDbContext : DbContextBase 
    { 
     public CustomDbContext() 
      : base("theconnectionstringwedontwanttoset") //hardcoded connection string 
     { 
     } 

,我們需要硬編碼構造函數的事實是我們不能用,因爲在我們的客戶端應用程序,我們沒有一個配置文件工作,我們動態地建立連接,因爲我們連接到多個不同的數據庫(服務器,本地sql compact)。

在研究了DbMigrationsConfiguration類之後,我發現了一個名爲TargetDatabase的DbConnectionsInfo屬性,它可以在構造函數中設置。但即使這個解決方案沒有奏效。這是我做過什麼:

public sealed class Configuration : DbMigrationsConfiguration<CustomDbContext> 
    { 
     public Configuration() 
     { 
      AutomaticMigrationsEnabled = true; 
      //Setting the TargetDatabase in the hope it will use it in the migration 
      TargetDatabase = new DbConnectionInfo("Server=xxx;Database=xxx;Trusted_Connection=True", "System.Data.SqlClient"); 
     } 


public class MigrationInitializer : MigrateDatabaseToLatestVersion<CustomDbContext, Configuration> 
    { 
    } 

我可以看到,最終Activator.CreateInstance用於內DbMigrator,我從這個類有望使用TargetDatabase.Create ......什麼的。

歡迎任何幫助或反饋。

由於提前,

Wilko

+0

嗨Wilkokosten。你有沒有想出解決這個問題的方法?我面臨着同樣的問題。 – Gary

+0

你使用什麼版本的EF? – Mark

回答

相關問題