Getting a SQL connection using Entity Framework

c# entity-framework

Question

Given directly closing connections in Entity Framework and http://msdn.microsoft.com/en-us/library/bb738582%28v=vs.90%29.aspx, it would seem that I should instead be leveraging the context to make connections rather than the following.

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

According to what I understand, I'll

  • Remove the connection string.
  • Use the connection pooling that EF offers.

However, how can I get a SQL connection through the context?

1
11
5/23/2017 11:55:19 AM

Accepted Answer

I learned that the magic number is ExecuteStoreCommand().

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

When this happens, an explicit Connection is not required, which really makes the code much clearer. All of the following code was replaced with the one-liner above.

  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();
    }
  }
9
3/12/2011 11:36:06 PM

Popular Answer

The connection would be returned in EF5 (as opposed to EF6) by doing the following:

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

You probably won't ever require an inner database connection if you use EF correctly.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow