ASP.NET EntityFramework get database name
Solution 1
This should do the job for you
string databaseName = context.Database.Connection.Database;
Solution 2
For those of you who are using EF core can do this as an alternative:
var databaseName = context.Database.GetDbConnection().Database
Related videos on Youtube
Lion
Updated on August 01, 2022Comments
-
Lion almost 2 years
I created an ASP.NET EF application with MySQL using the following tutorial: http://www.asp.net/identity/overview/getting-started/aspnet-identity-using-mysql-storage-with-an-entityframework-mysql-provider Its working but I don't like to set the name of my database hardcoded in the MySqlInitializer class - called myDatabaseName in the following snippet:
var migrationHistoryTableExists = ((IObjectContextAdapter)context).ObjectContext.ExecuteStoreQuery<int>( string.Format( "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = '{0}' AND table_name = '__MigrationHistory'", "myDatabaseName"));
I'm looking for a way to get the name of the database from the DbContext dynamically so that I store the database-name only in the connection-string and not a second time in my MySqlInitializer. But I can't find any attribute for the name, neither in the DbContext nor in the Database-attribute of the DbContext.
-
DMX David Cardinal over 3 yearsThis is not up to date with EF Core 5.0
-
johnny 5 over 3 years@DMXDavidCardinal What has changed in EF Core 5.0?
-
DMX David Cardinal over 3 yearsI never used the previous versions so I can't really compare effectively, but the
DbContext.Database
property is of typeDatabaseFacade
which does not contain the methodGetDbConnection()
. The SQL Connection is now defined in a protectedOnConfiguring
method using aDbContextOptionsBuilder
. However, this optionsBuilder doesnt not seem to be accessible outside the DbContext class. -
johnny 5 over 3 years@DMXDavidCardinal It doesn't include the method because it's an extension method. See the MSDN Documentation
-
DMX David Cardinal over 3 yearsAh! Thanks! Sounds pertinent enough to add to the solution IMO
-
ADM-IT about 2 yearsmake sure you have
using Microsoft.EntityFrameworkCore;
, otherwise you won't haveGetDbConnection()
method available.