How to choose DbConfigurationType programatically?

c# entity-framework-6

Question

I have a DbContext:

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

Now, what if I want to be able to use another DbConfigurationType, according to AppSettings value?

So that, I change AppSettings value from MySQL to MSSQL and it becomes:

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

Of course, I can create a factory, and use reflection to create a new class with custom attribute. However, is there a solution without reflection?

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

Accepted Answer

I have solved the problem by inheriting from 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
{

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

Popular Answer

You can replace the attribute with the registration at runtime intercepting the configuration before it's locked:

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