Join GitHub today
GitHub is home to over 36 million developers working together to host and review code, manage projects, and build software together.Sign up
GetDbConnection() and connection pool management #7810
Hi, I've seen many uses of GetDbConnection() wrapped in a using block. Since disposing the returned connection closes it, I am expecting this is required for some resource management in the connection pool but I've found no explicit explanation of what GetDbConnection does internally (ex: increment a reference counter) and if the "using" is really required in case DI is used for managing the (scoped) lifecycle of the DbContext.
But this causes problems since after the "using" EF does not work anymore (the connection is closed) in the same scope (asp next controller). I was considering if the using can be removed and still not cause any connection leak:
i.e., can the using be safely removed and still expect connection to be properly handled when the asp net controller method using the DbContext has completed?
@bragma If EF creates the DbConnection object, then EF will ensure it is disposed when the DbContext is disposed. On the other hand, if some other code creates the DbConnection object and passes it to EF, then it is the responsibility of the other code to also dispose the connection appropriately.
Similar rules apply to opening and closing the connection. If EF opens the connection, then EF will close the connection when it is done with it. If your code opens the connection, then your code should close the connection.
Sorry, I have mistakenly deleted my second question. As a reference, I am adding it back:
Answer by @ajcvickers is:
"Yes, although it would be considered best practice to pair an explicit open and close."
Thanks a lot!
I was having the same issue as above and changed my code to the following. When the context.Database.GetDbConnection() is called in a Using Statement, it works the first time, but all subsequent calls to cn.Close on that Connection will fail. So I modified my code to NOT use the Using Statement and it worked. Hope this helps someone.
public static DataTable GetDataTable (this DbContext context, string sql, Dictionary<string, object> parameters)