【问题标题】:How to choose DbConfigurationType programmatically?如何以编程方式选择 DbConfigurationType?
【发布时间】:2019-01-19 22:49:41
【问题描述】:

我有一个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; }
}

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

【问题讨论】:

标签: c# entity-framework-6


【解决方案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
{

}

【讨论】:

    【解决方案2】:

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

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

    Source

    【讨论】:

      猜你喜欢
      • 2020-06-15
      • 1970-01-01
      • 1970-01-01
      • 2014-06-29
      • 1970-01-01
      • 2019-03-14
      • 2016-12-05
      • 2011-09-06
      相关资源
      最近更新 更多