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

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.

2
  • 3
    context.Connection was removed since EF6 Commented Sep 17, 2015 at 7:46
  • 4
    @RomanPokrovskij in EF6 you can use context.Database.Connection
    – Sÿl
    Commented Jul 18, 2016 at 14:24
11

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

var connection = Context.Database.Connection;
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
  • 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. Commented Mar 12, 2011 at 23:39
  • It was deleted as the problem got messed up in the question. Can you repose the answer here and I'll accept it Commented Mar 12, 2011 at 23:45
  • I already voted there for reopen so I will wait if other users with high rep. will vote as well before making duplicit answer. Commented Mar 12, 2011 at 23:48
8
var efConnectionStringBuilder = new EntityConnectionStringBuilder(efConnectionString);
string sqlConnectionString = efConnectionStringBuilder.ProviderConnectionString;
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;
0
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);
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
}
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
  • Yes, but I wanted to fire an UPDATE statement without first reading in the entity - hence I need an SQLConnection Commented Mar 12, 2011 at 22:53
  • it connects automaticly so to speak , you can fire the update and its then when EF connects.(unless you do other stuff before that ) Commented Mar 12, 2011 at 23:03

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.