如何以编程方式选择DbConfigurationType?

时间:2016-07-12 11:41:02

标签: c# entity-framework-6

我有DbContext

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

现在,如果我想根据AppSettings值使用另一个DbConfigurationType怎么办?

这样,我将AppSettings值从MySQL更改为MSSQL,它变为:

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

当然,我可以创建一个工厂,并使用反射创建一个具有自定义属性的新类。但是,有没有反思的解决方案吗?

2 个答案:

答案 0 :(得分: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
{

}

答案 1 :(得分:0)

您可以在运行时使用注册替换属性,在锁定之前拦截配置:

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

Source