如何以编程方式选择 DbConfigurationType?

编程入门 行业动态 更新时间:2024-10-09 07:17:31
本文介绍了如何以编程方式选择 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?

本文发布于:2023-11-05 02:56:39,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1559717.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:方式   DbConfigurationType

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!