7

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.

usr-local-ΕΨΗΕΛΩΝ
  • 26,101
  • 30
  • 154
  • 305

1 Answers1

5

Did you use this ?

DbContext.Database.Connection.GetType().Name

If yes, what is the tricky part ?

mybirthname
  • 17,949
  • 3
  • 31
  • 55
  • That object is always an instance of `EntityConnection`. Tricky means that I don't like using reflection. It is prone to errors. Surely there is no _easy_ "GetDbType()=="MYSQL" API haha – usr-local-ΕΨΗΕΛΩΝ Jul 10 '15 at 15:31
  • 1
    The `Connection` property does not exist in `Microsoft.EntityFrameworkCore`. – robyaw Nov 12 '21 at 09:38