Determine at runtime which db provider is being used, with EF Core

asp.net asp.net-core c# entity-framework entity-framework-core

Question

In our ASP.NET Core and EF Core system, we use different databases for different parts of the system. I need to be able to tell, at runtime, which db provider is being used, because some stuff needs to take this into account.

During startup, there is this for SQL Server:

  services.AddDbContext<MyContext>(
    options => options.UseSqlServer(config.GetConnectionString("DefaultConnection"))
  );

or this for SQLite:

  services.AddDbContext<MyContext>(
    options => options.UseSqlite(config.GetConnectionString("DefaultConnection"))
  );

The point being that the knowledge of which database is being used, is contained within the system, somewhere.

At some arbitrary point in the system, how can I determine which database I'm using? I have access to the MyContext. Is there something in there that can reveal this info?

1
7
11/16/2016 1:01:20 AM

Accepted Answer

Anywhere in the system, where you have access to the MyContext, do this:

context.Database.GetDbConnection().GetType().Name

For example, it is SqliteConnection for SQLite, or SqlServerConnection for SQL Server, etc.

However I'm not sure if you'll need to dispose the connection afterwards!

7
11/16/2016 8:30:54 AM

Popular Answer

I use in my project 3 database providers.

  • Npgsql.EntityFrameworkCore.PostgreSQL
  • Microsoft.EntityFrameworkCore.SqlServer
  • Pomelo.EntityFrameworkCore.MySql

Include in your client project, that references, can be added from Nuget Package manager.

The references contains the following extension methods.

Boolean isPostgreSQL = context.Database.IsNpgsql();
Boolean isSqlServer = context.Database.IsSqlServer();
Boolean isMySql = context.Database.IsMySql();


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow