[英]Get the database type from EntityFramework's `DbContext`
The question is really simple: given an instance of an EntityFramework's DbContext
, I would like to tell between the effective database it is connected do. 问题很简单:给定一个EntityFramework的
DbContext
实例,我想在它所连接的有效数据库之间做什么。 AFAIK there are current implementations of EF providers for SQL Server, by Microsoft, MySQL, from Oracle, and perhaps for Postgres. AFAIK目前有针对SQL Server的EF提供程序的实现,由Microsoft,MySQL,Oracle和Postgres提供。
Let's assume I have access "only" to the DbContext
instance in my method. 假设我在我的方法中只“访问”了
DbContext
实例。 How do I detect that I am working with MSSQL, MySQL, Postgres, etc.? 我如何检测到我正在使用MSSQL,MySQL,Postgres等? (I wonder if there is an Oracle client for EF, that would add up)
(我想知道是否有一个用于EF的Oracle客户端,这会加起来)
Currently I can try with some reflection: 目前我可以尝试一些反思:
DbContext.Connection
is normally an instance of EntityConnection
DbContext.Connection
通常是EntityConnection
一个实例 EntityConnection
exposes StoreConnection
property, which should be our ADO connection. EntityConnection
公开StoreConnection
属性,该属性应该是我们的ADO连接。 testing it against known classes (like MySqlConnection
) should work MySqlConnection
)进行测试应该可行 However I believe that this approach is a little tricky. 但是我相信这种方法有点棘手。 A normal App.config contains the following:
普通的App.config包含以下内容:
<providers>
<provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6" />
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
I am a little confused, I hoped EF had a better API to detect database type in case one needs to perform uncommon operations. 我有点困惑,我希望EF有一个更好的API来检测数据库类型,以防需要执行不常见的操作。
My question is if there is a simpler method. 我的问题是,是否有一个更简单的方法。
Did you use this ? 你用过这个吗?
DbContext.Database.Connection.GetType().Name
If yes, what is the tricky part ? 如果是,那么棘手的部分是什么?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.