2016-07-12 17 views
0

Ich habe ein DbContext:Wie wählt man DbConfigurationType programmatisch?

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

Nun, was ist, wenn ich will eine andere DbConfigurationType, zu verwenden, um der Lage sein Wert nach AppSettings?

Damit ändere ich AppSettings Wert MySQL-MSSQL und es wird:

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

Natürlich kann ich eine Fabrik erstellen und verwenden Reflexion eine neue Klasse mit benutzerdefinierten Attribut zu erstellen. Gibt es jedoch eine Lösung ohne Reflexion?

+0

@ Uno die Konfigurationstypen sind unterschiedlich, 'MySqleEFConfiguration' vs' MsSqleEFConfiguration' – stuartd

+0

Verzeihung! Meine faulen Augen ... –

+0

Werfen Sie einen Blick auf diese Antwort: http://stackoverflow.com/questions/20354083/ef6-and-multiple-configurations-sql-server-and-sql-server-compact –

Antwort

1

I gelöst haben das Problem durch Erben von 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

Sie können das Attribut mit der Registrierung zur Laufzeit ersetzen, die die Konfiguration abfängt, bevor es gesperrt ist:

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

Source