2016-07-12 190 views
0

我有一個DbContext如何以編程方式選擇DbConfigurationType?

[DbConfigurationType(typeof(MySqlEFConfiguration))] 
public class MyDbContext : DbContext 
{ 
    public DbSet<MyClass> MyClasses { get; set; } 
} 

現在,如果我希望能夠用另一種DbConfigurationType什麼,根據AppSettings的價值?

這樣,我的AppSettings值改爲從MySQLMSSQL它變成:

[DbConfigurationType(typeof(MsSqlEFConfiguration))] 
public class MyDbContext : DbContext 
{ 
    public DbSet<MyClass> MyClasses { get; set; } 
} 

當然,我可以創建一個工廠,使用反射來創建自定義屬性的新類。但是,有沒有反思的解決方案?

+0

@ Uno的配置類型不同,'MySqlEFConfiguration' vs'MsSqlEFConfiguration' – stuartd

+0

請原諒!我懶惰的眼睛... –

+0

看看這個答案︰http://stackoverflow.com/questions/20354083/ef6-and-multiple-configurations-sql-server-and-sql-server-compact –

回答

1

我已經從DbConfigurationTypeAttribute繼承解決了這個問題:

public class BaseEfConfiguration : DbConfigurationTypeAttribute 
{ 
    public BaseEfConfiguration() : base(SqlConfiguration) 
    { 
    } 

    public static Type SqlConfiguration 
    { 
     get 
     { 
      string databaseTypeName = ConfigurationManager.AppSettings["DatabaseType"]; 
      switch (databaseTypeName) 
      { 
       case "MySQL": 
        return typeof(MySqlEFConfiguration); 
       case "MSSQL": 
        return typeof(MsSqlEFConfiguration); 
       default: 
        throw new NotImplementedException($"No such SQL configuration type {databaseTypeName}"); 
      } 
     } 
    } 
} 

[BaseEfConfiguration] 
public class BaseDbContext : DbContext 
{ 

} 
0

之前它鎖定您可以替換在運行時攔截的配置註冊屬性:

DbConfiguration.Loaded += (_, a) => 
    { 
     a.ReplaceService<DbProviderServices>((s, k) => new MyProviderServices(s)); 
     a.ReplaceService<IDbConnectionFactory>((s, k) => new MyConnectionFactory(s)); 
    }; 

Source