Friday, August 30, 2013

Getting the database name from an Entity Framework Context

This seems like it should be so easy, but it took awhile to figure out.  Both methods below take an ObjectContext.  You can get that from a DbContext using ((IObjectContextAdapter)myDbContext).ObjectContext.


public static string ADOConnectionString( ObjectContext context )
{
    return ( (EntityConnection)context.Connection ).StoreConnection.ConnectionString;
}

/// This works regardless of how the connection string names the database ("initial catalog", "database", etc.).
public static string DatabaseName( ObjectContext context )
{
    return new SqlConnectionStringBuilder( ADOConnectionString( context ) ).InitialCatalog;
}

No comments: