EntityFramework 自定义SQL查询
var sql = @"select * from A where 1=1 ";
var paramList = new List<SqlParameter>();
if (!string.IsNullOrEmpty(code))
{
sql += " AND code like @CODE";
paramList.Add(new SqlParameter("@CODE", $"%{code}%"));
}
1、获取总条数
var countSql = $"Select count(1) from {sql} "
dbContext.Database.SqlQuery<int>(countsql, paramList.ToArray()).FirstOrDefault()
2、获取记录
var pageSql =$"SELECT * FROM ( SELECT *, ROW_NUMBER() OVER (ORDER BY 排序条件) AS RowNum FROM {sql} ) AS tempTable WHERE RowNum BETWEEN { (pNumber-1)* pSize+1 } AND pNumber*pSize} ";
dbContext.Database.SqlQuery<Entity>(sql, paramList.ToArray()).ToList()
第二次查询报错:另一个 SqlParameterCollection 中已包含 SqlParameter。
解决方案:
dbContext.Database.SqlQuery<Entity>(sql, paramList.Select(x => ((ICloneable)x).Clone()).ToArray()).ToList()
网友评论