The ConnectionString property has not been initialized

后端 未结 1 1823
庸人自扰
庸人自扰 2021-01-12 13:17

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

1条回答
  •  说谎
    说谎 (楼主)
    2021-01-12 13:42

    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;
    

    0 讨论(0)
提交回复
热议问题