我正在使用实体框架进行 2 个查询,一个接一个,第一个总是工作正常,但第二个总是返回我:ConnectionString 属性尚未初始化。
如果我改变方法的顺序,同样的事情会发生,第一个工作正常,第二个抛出这个异常。
我在页面中使用的代码如下:
> var count = RequestBaseBL.GetGenericResultsCount(query.QuerySql);
>
> var datatable = RequestBaseBL.GetGenericResults(query.QuerySql, 0);
在我的 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"];
}
}