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.
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
is normally an instance of EntityConnection
EntityConnection
exposes StoreConnection
property, which should be our ADO connection. testing it against known classes (like MySqlConnection
) should workHowever 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>
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.
A DbContext instance represents a combination of the Unit Of Work and Repository patterns such that it can be used to query from a database and group together changes that will then be written back to the store as a unit. DbContext is conceptually similar to ObjectContext.
DbContext is an important class in Entity Framework API. It is a bridge between your domain or entity classes and the database. DbContext is the primary class that is responsible for interacting with the database.
The DbContext class is an integral part of Entity Framework. An instance of DbContext represents a session with the database which can be used to query and save instances of your entities to a database. DbContext is a combination of the Unit Of Work and Repository patterns.
Did you use this ?
DbContext.Database.Connection.GetType().Name
If yes, what is the tricky part ?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With