56

In EF6 works this code:

    public string GetConnectionString(DbContext ctx)
    {
        ObjectContext _objectContext = ((IObjectContextAdapter)ctx).ObjectContext;
        if (_objectContext?.Connection != null)
        {
            EntityConnection entityConnection = _objectContext.Connection as EntityConnection;
            return entityConnection?.StoreConnection?.ConnectionString;
        }
        return null;
    }

How to do it in EF Core 2.0 ?

Cyrus
  • 2,261
  • 2
  • 22
  • 37

1 Answers1

131
var connectionString = ctx.Database.GetDbConnection().ConnectionString;

with EF Core 5:

   var connectionString = ctx.Database.GetConnectionString();
ErikEJ
  • 40,951
  • 5
  • 75
  • 115
  • 10
    thanks, found it in nuget package: `Microsoft.EntityFrameworkCore.Relational` – Cyrus Jul 28 '17 at 06:28
  • 5
    But it doesn't include the password. – Khodaie Aug 10 '19 at 08:13
  • 1
    @Khodaie, the password will be in there [until a connection is opened](https://stackoverflow.com/questions/12467335/connectionstring-loses-password-after-connection-open), unless you use Persist Security Info = true in your connection string. You could fetch the connection string in your context's constructor and store it in a private field, that way you have access to it later on. However, that defeats some of the added security, so be careful. – Christopher Sep 03 '19 at 19:05
  • 9
    In Ef Core 2.2 you need to add using Microsoft.EntityFrameworkCore; – mr_squall Sep 19 '19 at 14:14