77

We use Entity Framework 5, but have a requirement to ALSO use a normal database connection from the application for some custom SQL we need to perform.

So, I am creating a DatabaseAccess class which handles this connection. Is there a way that I can populate the connection string, by checking the Entity Framework connection string?

So:

SqlConnection cnn;
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password"

Can I build that from checking Entity Framework?

2
  • Are you using Code first, or an edmx file? Are you using ObjectContext of DbContext? Commented Oct 22, 2012 at 1:57
  • most answers below answer the wrong question - they propose to get connection from instantiated context when answer is "by checking the Entity Framework connection string" not the instance of context. you don't need to instantiate whole EF context machinery to get just a piece of string, essentially. You just need EntityConnectionStringBuilder from one of underrated answers Commented Oct 14, 2019 at 13:08

11 Answers 11

121

You can get the connectionstring used by EF by using the following:

MyDbContext.Database.Connection.ConnectionString

Or as mark says you can initalise the context with a sqlconnection

Sign up to request clarification or add additional context in comments.

6 Comments

This will show the EF connection string, which when using an edmx file is not usable by a standard SqlConnection.
That's not true either. You can use DbContext with an edmx file, and you will still have an EntityConnection string rather than a Database ConnectionString when using this method.
You don't seem to be understanding my point. If you are using DbContext and an edmx file, then the ConnectionString property you mention will NOT contain a SqlConnection compatible connection string. It will have an EntityConnection string, which includes metadata strings and what not. So no, your method, if using DbContext and an edmx file will not allow someone to take the connection string and use it with a SqlConnection.
Thanks for this advice @luke-mcgregor. It is finally the only working solution I found for my problem. The connection string of entity framework is a non standard one, but using this property, it will return a good and formatted connection string that I can use with SqlConnection or OracleConnection.
It wont bring password.
|
77

Here's how to get the connection string in EF 5, EF 6 and EF Core 1/EF 7.

//Entity Framework 5
myContext.Database.Connection.ConnectionString
//Entity Framework 6
myContext.Database.Connection.ConnectionString
//Entity Framework Core 1
myContext.Database.GetDbConnection().ConnectionString

For more details see - http://nodogmablog.bryanhogan.net/2016/04/entity-framework-checking-the-connection-string-of-your-context/

Comments

20

//Entity Framework 5

myContext.Database.Connection.ConnectionString

//Entity Framework 6

myContext.Database.Connection.ConnectionString

//Entity Framework Core 1

myContext.Database.GetDbConnection().ConnectionString

1 Comment

EF 6 I needed: myContext.Database.GetConnectionString()
19

Yes you can.

See here for 3 options.

1 - use separate connection string for each

2 - extract it from your entity object (this is what i think you want)

3 - use the entity object to execute your custom SQL

Here's how to do nr 2:

using System.Data.EntityClient;
using System.Data.SqlClient;
...
private string GetADOConnectionString()
{
    SalesSyncEntities ctx = new SalesSyncEntities(); //create your entity object here
    EntityConnection ec = (EntityConnection)ctx.Connection;
    SqlConnection sc = (SqlConnection)ec.StoreConnection; //get the SQLConnection that your entity object would use
    string adoConnStr = sc.ConnectionString;
    return adoConnStr;
}

2 Comments

Couldn't you use just ctx.Connection.ConnectionString?
@Wimpie Ratte, This is perfect. It gives the exact connection string. PS: EntityConnection comes under System.Data.EntityClient namespace.
11

Do you mean, can you use a SqlConnection with your EF DbContext?

The DbContext class has a constructor where you can pass in a SqlConnection, and then tell EF whether or not it owns it.

var YourContext = new YourContext(SqlConnection, true);

2 Comments

That assumes it's a DbContext, which isn't the default for most people using VS2010 or 2008. ObjectContext has no such constructor.
This answer proposes to instantiate whole EF context just to get piece of string from EF connection string. Not even considering it's IDisposable...
11

even in EF3 you can use EntityConnectionStringBuilder.

EntityConnectionStringBuilder conn = 
    new EntityConnectionStringBuilder(DBEntities.dbConnection);
SqlConnection s = new SqlConnection(conn.ProviderConnectionString);

1 Comment

I used this but read the ef string from web.config instead of DBEntities.dbConnection. Excelent thx
6

Hope it helps..

    private readonly ApplicationDbContext _applicationDbContext;
    string connectionString = string.Empty;

    public CommonService(ApplicationDbContext applicationDbContext)
    {
        _applicationDbContext = applicationDbContext;
        connectionString = _applicationDbContext.Database.GetDbConnection().ConnectionString;
    }

1 Comment

Please have a look at the other answers, there are already working solutions that solved OP's issue. :-)
5

I had this problem too, to solve the problem you can do this:

        SqlConnection con = context.Database.Connection as SqlConnection;
        SqlCommand command = new SqlCommand(sql, con);
        con.Open();

        SqlDataReader reader = command.ExecuteReader();
        while (reader.HasRows)
        {
            while (reader.Read())
            {
                //read your fields
            }

            reader.NextResult();
        }

        con.Close();

1 Comment

The essence is in the very first line - like it!
2

Here is a generic way of getting the connection string:

   public string GetConnString<T>(T ent)
            where T : ObjectContext
        {
            EntityConnection ec = (EntityConnection)ent.Connection;
            SqlConnection sc = (SqlConnection)ec.StoreConnection;
            return sc.ConnectionString;
        }

Then to use it would be:

 MyEntities ent = new MyEntities();
 String ConnString = GetConnString(ent);

Comments

1

In my case I just needed to execute an update statement so I used the following construct

_db.Database.ExecuteSqlCommand($"update ChiusureTurni set esportato = 1 where idChiusuraTurni = {idChiusura}");

where _db is my db context in this case I took advatage of transaction management

Comments

0

If you want to get the (SQL) connection string without instantiating the Entity Context/establishing an entity connection, we can use the EntityConnectionStringBuilder:

string entityConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings[entityName].ConnectionString;
var entitybuilder = new System.Data.EntityClient.EntityConnectionStringBuilder(entityConnectionString);
string sqlConnectionString = entitybuilder.ProviderConnectionString;

To get/set a component of the sql Connection string, replace the last line with:

var sqlBuilder = new System.Data.SqlClient.SqlConnectionStringBuilder(entitybuilder.ProviderConnectionString);
string sqlConnectionString = sqlBuilder.ConnectionString;
Console.WriteLine("Environment: " + sqlBuilder.DataSource);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.