The ConnectionString Property Was Not Initialized

I use an entity structure to make 2 requests, one after another, the first always works fine, but the second always returns me: The ConnectionString property has not been initialized.

If I change the order of the methods, the same thing happens, the first works fine, the second throws this exception.

The code I use on the page is as follows:

> var count = RequestBaseBL.GetGenericResultsCount(query.QuerySql); > > var datatable = RequestBaseBL.GetGenericResults(query.QuerySql, 0); 

and in my dal

 public int GetGenericResultsCount(string strsql) { using (var connection = (SqlConnection)_context.Database.Connection) { var adapter = new SqlDataAdapter(strsql, connection); var results = new DataSet(); adapter.Fill(results, "Results"); return results.Tables["Results"].Rows.Count; } } public DataTable GetGenericResults(string strsql, int pageIndex) { StringBuilder sb = new StringBuilder(); sb.Append("WITH MyPagedData as ( "); int indexFrom = strsql.IndexOf("from"); sb.Append(strsql.Substring(0, indexFrom)); sb.Append(", "); sb.Append("ROW_NUMBER() OVER(ORDER BY RequestBaseId DESC) as RowNum "); sb.Append(strsql.Substring(indexFrom)); sb.Append(") "); sb.Append("SELECT * from MyPagedData where RowNum between @StartIndex and @StartIndex + 10"); using(var connection = (SqlConnection)_context.Database.Connection) { var adapter = new SqlDataAdapter(sb.ToString(), connection); adapter.SelectCommand.Parameters.Add("@StartIndex", SqlDbType.Int).Value = pageIndex; var results = new DataSet(); adapter.Fill(results, "Results"); return results.Tables["Results"]; } } 
+4
source share
1 answer

In general, the using construct should be used when you create an object assigned to a variable, either using the new operator or the factory method. The Connection Database property in DbContext creates a connection only if it does not already exist; in all other cases, the property simply returns the existing one.

In your code, the first call gets a live connection, runs on it, and then closes it on a Dispose call implicitly executed using . At this point, the Database of DbContext has a link to the selected object. The second call takes this released object and tries to use it, causing an error.

To fix this, simply replace using with the assignments:

 var connection = (SqlConnection)_context.Database.Connection; 
+7
source

Source: https://habr.com/ru/post/1416326/


All Articles