14

In the light of Closing connections explicitly in Entity Framework and http://msdn.microsoft.com/en-us/library/bb738582%28v=vs.90%29.aspx it seems that I should be using the context to create connections rather than doing the following

using (SqlConnection con = new SqlConnection("Persist Security Info=False;Integrated Security=true;Initial Catalog=Remember;server=(local)"))
{
    ...
}

My understanding is that I'll

  • Get rid of the connection string
  • Utilize connection pooling built into EF

But how do I acquire an SQL connection through the context?

2
  • What do you want the SQL Connection for? There's probably a way to do what you want directly in EF without the need for the actual SqlConnection. Commented Aug 1, 2014 at 15:01
  • Possible duplicate of Extract connection string from an Entity Connection String Commented Mar 7, 2017 at 3:54

8 Answers 8

20

In EF5 (changed for EF6) the following would return the connection:

var connection = ((EntityConnection)context.Connection).StoreConnection;

If you are using EF in a right way you will probably never need to get inner db connection.

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

2 Comments

context.Connection was removed since EF6
@RomanPokrovskij in EF6 you can use context.Database.Connection
11

I used next code to getting connection (Entity Framework 5.0):

var connection = Context.Database.Connection;

Comments

9

I found out that the magic lies in ExecuteStoreCommand()

  new AdventureEntities().ExecuteStoreCommand(
        @"    UPDATE Users
              SET lname = @lname 
              WHERE Id = @id",
        new SqlParameter("lname", lname), new SqlParameter("id", id));

Then there is no need for an explicit Connection, it actually made the code a lot cleaner. The one-liner above replaced all of the following code

  using (SqlConnection con = new SqlConnection("Persist Security Info=False;Integrated Security=true;Initial Catalog=Remember;server=(local)"))
  {
    con.Open();
    using (SqlCommand cmd = con.CreateCommand())
    {
      cmd.CommandText = @"
          UPDATE Users
          SET lname = @lname 
          WHERE Id = @id";
      cmd.Parameters.AddWithValue("lname", lname);
      cmd.Parameters.AddWithValue("id", id);
      cmd.ExecuteNonQuery();
    }
  }

3 Comments

Yes that was one solution I described in question you deleted. But there is even one better without calling SQL manually. Check ObjectStateManager, GetObjectStateEntry, ObjectStateEntry and SetModifiedProperty.
It was deleted as the problem got messed up in the question. Can you repose the answer here and I'll accept it
I already voted there for reopen so I will wait if other users with high rep. will vote as well before making duplicit answer.
8
var efConnectionStringBuilder = new EntityConnectionStringBuilder(efConnectionString);
string sqlConnectionString = efConnectionStringBuilder.ProviderConnectionString;

Comments

5

If the EF connection string is stored in your web config file, you can assign it to a SQL Data Source with this code:

            var connString = ConfigurationManager.ConnectionStrings["MyDataEntities"].ConnectionString;
            EntityConnection ec = new EntityConnection(connString);
            var storeConnect = ec.StoreConnection;

            SqlDataSource1.ConnectionString = storeConnect.ConnectionString;

Comments

4

I believe the easiest way to create a SqlConnection in EF6 is to do the following:

DBContext context = new DBContext();
SqlConnection sqlconn = new SqlConnection(context.Database.Connection.ConnectionString);

Comments

1

You could use the following as well. I wanted to inject some Dapper.NET into a existing project that already had Entity framework entity context so I created the following:

public class EFConnectionAccessor : IDisposable
{
    private readonly SqlConnection sqlConnection;
    private readonly MyEntities entities;

    public EFConnectionAccessor()
    {
        entities = new MyEntities();

        var entityConnection = entities.Connection as EntityConnection;

        if (entityConnection != null)
        {
            sqlConnection = entityConnection.StoreConnection as SqlConnection;
        }
    }

    public SqlConnection connection
    {
        get
        {
            sqlConnection.Open();
            return sqlConnection;
        }
    }

    public void Dispose()
    {
        sqlConnection.Close();
        sqlConnection.Dispose();
        entities.Dispose();
    }
}

Called using

using (SqlConnection sqlConnection = new EFConnectionAccessor().connection)
{
 // ADO.NET CODE HERE - Or in my case dapper.net
}

Comments

0

the DataContext will allow you to call your Entity Objects right off of your DataContext reference, abstracting away all of the details of the underlying connection logistics.

2 Comments

Yes, but I wanted to fire an UPDATE statement without first reading in the entity - hence I need an SQLConnection
it connects automaticly so to speak , you can fire the update and its then when EF connects.(unless you do other stuff before that )

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.