64

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.

2 Answers 2

96

For those of you who are using EF core can do this as an alternative:

var databaseName = context.Database.GetDbConnection().Database
6
  • This is not up to date with EF Core 5.0 Commented Jan 17, 2021 at 4:35
  • @DMXDavidCardinal What has changed in EF Core 5.0?
    – johnny 5
    Commented Jan 18, 2021 at 14:45
  • 2
    I never used the previous versions so I can't really compare effectively, but the DbContext.Database property is of type DatabaseFacade which does not contain the method GetDbConnection(). The SQL Connection is now defined in a protected OnConfiguring method using a DbContextOptionsBuilder. However, this optionsBuilder doesnt not seem to be accessible outside the DbContext class. Commented Jan 18, 2021 at 16:01
  • 2
    @DMXDavidCardinal It doesn't include the method because it's an extension method. See the MSDN Documentation
    – johnny 5
    Commented Jan 18, 2021 at 16:28
  • 2
    make sure you have using Microsoft.EntityFrameworkCore;, otherwise you won't have GetDbConnection() method available.
    – ADM-IT
    Commented Mar 30, 2022 at 15:32
63

This should do the job for you (works up to .NET 6)

string databaseName = context.Database.Connection.Database;
1
  • 6
    Does not work with .NET 7.0 anymore. Commented Feb 21, 2023 at 14:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.