从EntityFramework的`DbContext`获取数据库类型。 [英] Get the database type from EntityFramework's `DbContext`
问题描述
这个问题真的很简单:给定EntityFramework的 DbContext
的实例,我想在它所连接的有效数据库之间进行区分。 AFAIK目前有Microsoft,MySQL,Oracle以及Postgres的SQL Server EF提供程序的当前实现。
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. AFAIK there are current implementations of EF providers for SQL Server, by Microsoft, MySQL, from Oracle, and perhaps for Postgres.
我们假设我只能访问我的方法中的 DbContext
实例。如何检测到我正在使用MSSQL,MySQL,Postgres等? (我想知道是否有一个用于EF的Oracle客户端,这会加起来)
Let's assume I have access "only" to the DbContext
instance in my method. How do I detect that I am working with MSSQL, MySQL, Postgres, etc.? (I wonder if there is an Oracle client for EF, that would add up)
目前,我可以尝试一下:
Currently I can try with some reflection:
-
DbContext.Connection
通常是EntityConnection
-
EntityConnection
公开StoreConnection
属性,该属性应该是我们的ADO连接。针对已知类(例如MySqlConnection
)进行测试应该可以
DbContext.Connection
is normally an instance ofEntityConnection
EntityConnection
exposesStoreConnection
property, which should be our ADO connection. testing it against known classes (likeMySqlConnection
) should work
但是我相信这种方法有点棘手。普通的App.config包含以下内容:
However I believe that this approach is a little tricky. A normal App.config contains the following:
<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>
我有点困惑,我希望EF有更好的API可以在需要时检测数据库类型
I am a little confused, I hoped EF had a better API to detect database type in case one needs to perform uncommon operations.
我的问题是是否有更简单的方法。
My question is if there is a simpler method.
推荐答案
您使用此吗?
DbContext.Database.Connection.GetType().Name
如果是,那么棘手的部分是什么?
If yes, what is the tricky part ?
这篇关于从EntityFramework的`DbContext`获取数据库类型。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!