Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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 work

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>

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.

like image 792
usr-local-ΕΨΗΕΛΩΝ Avatar asked Jul 10 '15 15:07

usr-local-ΕΨΗΕΛΩΝ


People also ask

What is DB context class?

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.

Where is DbContext in Entity Framework?

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.

Is DbContext part of Entity Framework?

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.


1 Answers

Did you use this ?

DbContext.Database.Connection.GetType().Name

If yes, what is the tricky part ?

like image 166
mybirthname Avatar answered Sep 28 '22 07:09

mybirthname