I’m using Entity Framework 4.x. When using a single instance of a Context for repeatedly querying the database in a single business operation, I know that Entity Framework will open and close the database connection for each query. But my question is, will the connection for all three queries (again, the same instance of the Context) be the same connection to the Database? Or will it grab another connection (potentially a poisoned one) from the Connection Pool?
Example 1:
var conn = (SqlConnection) ((EntityConnection) Context.Connection).StoreConnection;
conn.Open();
var A = new SqlCommand("exec SProcA", conn).ExecuteNonQuery();
conn.Close();
Thread.Sleep(100);
conn.Open();
var B = new SqlCommand("exec SProcB", conn).ExecuteNonQuery();
conn.Close();
Thread.Sleep(100);
conn.Open();
var C = new SqlCommand("exec SProcC", conn).ExecuteNonQuery();
conn.Close();
Example 2:
// Let Entity Framework manage my connections for me automagically.
var A = Context.TableA.First();
var B = Context.TableB.First();
var C = Context.TableC.First();
In these scenarios, will A, B, and C use the same real connection to the database or does Connection Pooling abstract this away from me?
After some testing, it seems that it is indeterminable whether or not you keep working with the same connection. Many times you do but seems like sometimes you don’t. Could be concurrency-related. Ultimately, it’s probably safest to assume that it’s ambiguous and will change.