EntityFramework 4使用存储过程分页

时间:2020-12-18 14:29:20
 CREATE PROC usp_OrgPage_SQL
@pageIndex INT,
@pageSize INT,
@totalCount INT OUTPUT
AS
BEGIN
SET @totalCount = (SELECT COUNT(*) FROM dbo.Organization)
SELECT * FROM
(
SELECT *,ROW_NUMBER() OVER(ORDER BY OrganizationID DESC)AS row FROM dbo.Organization
)AS res
WHERE res.row BETWEEN @pageSize * (@pageIndex - 1) + 1 AND @pageSize * @pageIndex
END

EntityFramework 4使用存储过程分页

EntityFramework 4使用存储过程分页

 public List<OrganizationModel> SelectPageList(int pageIndex, int pageSize, out int totalCount)
{
var cmd = DbContext.Connection.CreateCommand();
cmd.CommandText = "kydContext.usp_OrgPage_SQL";
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.Add(new EntityParameter
{
ParameterName = "pageIndex",
Value = pageIndex
});
cmd.Parameters.Add(new EntityParameter
{
ParameterName = "pageSize",
Value = pageSize
});
cmd.Parameters.Add(new EntityParameter
{
ParameterName = "totalCount",
Direction = System.Data.ParameterDirection.Output
}); cmd.Connection.Open();
DbDataReader reader = cmd.ExecuteReader(System.Data.CommandBehavior.SequentialAccess);
List<OrganizationModel> organizationModelList = new List<OrganizationModel>();
while (reader.Read())
{
OrganizationModel organizationModel = new OrganizationModel();
organizationModel.OrganizationID = reader.GetInt32(reader.GetOrdinal("OrganizationID"));
organizationModel.OrganizationName = reader.GetString(reader.GetOrdinal("OrganizationName"));
organizationModelList.Add(organizationModel);
}
reader.Close();
totalCount = Convert.ToInt32(cmd.Parameters["totalCount"].Value);
cmd.Connection.Close();
return organizationModelList;
}

对于EntityFramework调用存储过程通常想到的是"Context.ExcuteFunction()"。

EntityFramework 4使用存储过程分页

但是ExcuteFunction不返回任何结果,只有影响的行数,所以如果是通过存储过程实现分页及查询还得使用传统的command方式