61

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 ?

0

1 Answer 1

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

with EF Core 5:

 var connectionString = ctx.Database.GetConnectionString(); 
Sign up to request clarification or add additional context in comments.

5 Comments

thanks, found it in nuget package: Microsoft.EntityFrameworkCore.Relational
But it doesn't include the password.
@Khodaie, the password will be in there until a connection is opened, 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.
In Ef Core 2.2 you need to add using Microsoft.EntityFrameworkCore;
Without a using statement: Microsoft.EntityFrameworkCore.RelationalDatabaseFacadeExtensions.GetConnectionString(ctx.Database)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.