How to get database information with an entity database first?

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

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

But when I first make the database, the database is unavailable. How can I (from the code at runtime) go about getting the database connection string used by the entity infrastructure?

+5
source share
2 answers

The code:

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

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

ObjectContext API, :

var connection = context.Connection as EntityConnection;
if (connection == null) throw new ...;
var storeConnectionString = connection.StoreConnection.ConnectionString;
+12

... :

using System.Data.SqlClient;



    internal static string GetDatabaseName()
    {
        using (var _db = new MyProjectEntities())
        {
            return new SqlConnectionStringBuilder(_db.Database.Connection.ConnectionString).InitialCatalog;
        }
    }
+8

All Articles