ASP.NET EntityFramework get database name

asp.net c# entity-framework mysql

Question

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.

1
26
7/19/2015 8:02:13 PM

Accepted Answer

This should do the job for you

string databaseName = context.Database.Connection.Database;
39
7/19/2015 8:47:16 PM

Popular Answer

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

var databaseName = context.Database.GetDbConnection().Database


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