How to choose DbConfigurationType programmatically?(如何以编程方式选择 DbConfigurationType?)
问题描述
我有一个DbContext
:
[DbConfigurationType(typeof(MySqlEFConfiguration))]
public class MyDbContext : DbContext
{
public DbSet<MyClass> MyClasses { get; set; }
}
现在,如果我希望能够根据 AppSettings 值使用另一个 DbConfigurationType
怎么办?
Now, what if I want to be able to use another DbConfigurationType
, according to AppSettings value?
因此,我将 AppSettings 的值从 MySQL
更改为 MSSQL
,它变为:
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?
推荐答案
我已经通过继承DbConfigurationTypeAttribute
解决了这个问题:
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
{
}
这篇关于如何以编程方式选择 DbConfigurationType?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何以编程方式选择 DbConfigurationType?
基础教程推荐
- rabbitmq 的 REST API 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- MS Visual Studio .NET 的替代品 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01