Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET EntityFramework get database name

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.

like image 309
Lion Avatar asked Jul 19 '15 20:07

Lion


People also ask

How do I find the database name in Entity Framework?

ObjectContext. ExecuteStoreQuery<int>( string. Format( "SELECT COUNT(*) FROM information_schema. tables WHERE table_schema = '{0}' AND table_name = '__MigrationHistory'", "myDatabaseName"));

What is EntityFramework in asp net?

Entity Framework (EF) is an object-relational mapper that enables . NET developers to work with relational data using domain-specific objects. It eliminates the need for most of the data-access code that developers usually need to write. Get it: Add this to your project and start taking advantage of this powerful O/RM.


2 Answers

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

var databaseName = context.Database.GetDbConnection().Database 
like image 68
johnny 5 Avatar answered Sep 17 '22 13:09

johnny 5


This should do the job for you

string databaseName = context.Database.Connection.Database; 
like image 44
pkmiec Avatar answered Sep 19 '22 13:09

pkmiec