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?
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!
I use in my project 3 database providers.
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();