How to choose DbConfigurationType programatically?

c# entity-framework-6

Question

I possessDbContext :

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

What if I wish to use another device instead?DbConfigurationType based on the value of AppSettings?

I do this by changing the value of AppSettings toMySQL to MSSQL and it turns into:

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

Naturally, I could build a factory and then use reflection to build a new class with a unique characteristic. But is there a solution absent thought?

1
0
1/19/2019 2:49:41 PM

Accepted Answer

I've found a solution to the issue by deriving fromDbConfigurationTypeAttribute :

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
{

}
1
7/13/2016 2:59:11 PM

Popular Answer

In order to intercept the configuration before it is locked, you may replace the attribute with runtime registration:

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

Source



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow