7

When I use Entity Framework codefirst I can use the following code to get my database connection string:

var db = new dbContext();
Console.Writeline(db.Database.Connection.ConnectionString);

But when I do database first, Database is not available. How do I (from code at runtime) go about getting the database connection string that is being used by entity framework?

Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670
JonnyBoats
  • 5,177
  • 1
  • 36
  • 60

2 Answers2

12

The code:

var db = new dbContext();
Console.Writeline(db.Database.Connection.ConnectionString);

works always. So If you created entity model from your database and used DbContext Generator T4 template you can still use it.

If you instead used ObjectContext API you must call this:

var connection = context.Connection as EntityConnection;
if (connection == null) throw new ...;
var storeConnectionString = connection.StoreConnection.ConnectionString;
Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670
  • I never found this solution so I used to parse the querystring (which is not that well hidden ;-) ). This improved my code a lot, thanks! – Tillito Feb 11 '15 at 17:02
10

... And the specific connection string properties can then be exposed:

using System.Data.SqlClient;



    internal static string GetDatabaseName()
    {
        using (var _db = new MyProjectEntities())
        {
            return new SqlConnectionStringBuilder(_db.Database.Connection.ConnectionString).InitialCatalog;
        }
    }
Justin
  • 501
  • 5
  • 13