• [转]MVC 分页


    本内容代码段抄自传智视频

    /// <summary>
    /// 数据库分页
    /// </summary>
    static List<dynamic> GetPageList<T, TKey>(Expression<Func<T, dynamic>> select, Expression<Func<T, bool>> whereLambda, Expression<Func<T, TKey>> orderLambda, int pageSize, int pageIndex, out int total, bool isAsc)
        where T : class
    {
        StudyDBEntities context = new StudyDBEntities();
        total = context.Set<T>().Where(whereLambda).Count();
        var result = context.Set<T>().Where(whereLambda);
        if (isAsc)
            result = result.OrderBy(orderLambda);
        else
            result = result.OrderByDescending(orderLambda);
        return result.Skip(pageSize * (pageIndex - 1)).Take(pageSize).Select(select).ToList();
    }

    其中 total 返回符合条件的总行数

    result 返回符合条件的数据

    使用:

    int total = 0;
    var list = GetPageList<Student, int>(o => o, o => o.ID > 2, o => o.ID, 5, 5, out total, true);
    ViewData.Model = 实体
        .OrderBy(u => u.UserId)
        .Skip(pageSize * (pageIndex - 1))
        .Take(pageSize)
        .AsEnumerable();

    SQL 生成如下:

    SELECT 
        [GroupBy1].[A1] AS [C1]
        FROM ( SELECT 
            COUNT(1) AS [A1]
            FROM [dbo].[Student] AS [Extent1]
            WHERE [Extent1].[ID] > 2
        )  AS [GroupBy1]
    SELECT TOP (5) 
    [Filter1].[ID] AS [ID], 
    [Filter1].[Name] AS [Name], 
    [Filter1].[Class] AS [Class]
    FROM ( SELECT [Extent1].[ID] AS [ID], [Extent1].[Name] AS [Name], [Extent1].[Class] AS [Class], 
        row_number() OVER (ORDER BY [Extent1].[ID] ASC) AS [row_number]
        FROM [dbo].[Student] AS [Extent1]
        WHERE [Extent1].[ID] > 2
    )  AS [Filter1]
    WHERE [Filter1].[row_number] > 20
    ORDER BY [Filter1].[ID] ASC
  • 相关阅读:
    Flush the AOS cache from code
    EntityConnectionStringBuilder 构造EF连接字符串
    AX中文转拼音
    AX2012 AOT中Web部署显示二级以上菜单
    clearCompanyCache
    AX2009 打印到PDF优化
    AX ODBC读取其他SQL数据库服务器数据
    AX2009报表打印固定长度Barcode条码
    Create Product Variant
    Rename AOT Object
  • 原文地址:https://www.cnblogs.com/z5337/p/5260082.html
走看看 - 开发者的网上家园