方法返回的时候 要设置用list会比较稳妥。
遇到的问题:
private IDbConnection GetConnection()
{
var dataSettingsManager = new DataSettingsManager();
var dataProviderSettings = dataSettingsManager.LoadSettings();
_con = new SqlConnection(dataProviderSettings.DataConnectionString);
if (_con.State != ConnectionState.Open)
{
_con.Open();
}
return _con;
}
/// <summary>
/// 分页 使用 DapperExtensions
/// </summary>
/// <param name="pageNum"></param>
/// <param name="pageSize"></param>
/// <param name="outTotal"></param>
/// <param name="expression"></param>
/// <param name="sortList"></param>
/// <returns></returns>
public IEnumerable<T> GetPageData(int pageNum, int pageSize, out int outTotal,
Expression<Func<T, bool>> expression = null, object sortList = null, IDbTransaction dbTransaction = null, int commandTimeout = 10)
{
IEnumerable<T> entities = null;
using (var con = GetConnection())
{
IPredicateGroup predicate = DapperLinqBuilder<T>.FromExpression(expression); //转换Linq表达式
IList<ISort> sort = SortConvert(sortList);//转换排序接口
if (sort == null || sort.Count == 0)
{
sort.Add(new Sort { PropertyName = "ID", Ascending = false });
//sort = new List<ISort>();
}
entities = con.GetPage<T>(predicate, sort, pageNum - 1, pageSize, dbTransaction, commandTimeout);
outTotal = con.Count<T>(predicate);
con.Close();
return entities.ToList();;
}
}
重点在这边
entities = con.GetPage<T>(predicate, sort, pageNum - 1, pageSize, dbTransaction, commandTimeout);
如果直接返回的话 里面的con状态已经被释放,所以会报错 con数据连接未初始化。
只要在后面加一个 tolist() 这样把结果先返回存到内存。
折腾了一天才发现这个问题