I am using entity framework to make 2 queries, one after the another, the first one always works fine, but the second one always returns me: The ConnectionString property ha
In general, the using
construct should be used when you create an object assigned to the variable, either with the new
operator or though a factory method. The Connection
property of Database
in DbContext
creates the connection only if it does not exist already; in all other cases, the property simply returns an existing one.
In your code, the first invocation gets a "live" connection, operates on it, and then closes it through the call of Dispose
implicitly performed by using
. At this point, the Database
of DbContext
has a reference to a released object. The second invocation picks up that released object, and tries to use it, triggering an error.
To fix this, simply replace using
with assignments:
var connection = (SqlConnection)_context.Database.Connection;