Home Backend Development C#.Net Tutorial Tutorial on how to use Dapper to achieve paging effects

Tutorial on how to use Dapper to achieve paging effects

May 24, 2018 pm 04:47 PM
Pagination Effect

This article mainly introduces the paging effect based on Dapper in detail, supports filtering, sorting, total number of result sets, multi-table queries, and non-stored procedures. It has certain reference value. Interested friends can refer to it.

Introduction

I searched the blog in advance about the implementation of Dapper paging. There are some, but they are either based on stored procedures or support paging, but not Sorting is supported, or search criteria are not so easy to maintain.

Method definition

The following is my paging implementation. Although it is not generic (because of the where conditions and sql statement combinations), it should be considered It is more general. The method definition is as follows:

public Tuple<IEnumerable<Log>, int> Find(LogSearchCriteria criteria
      , int pageIndex
      , int pageSize
      , string[] asc
      , string[] desc);
Copy after login

The above function definition is an example of querying Log. In the returned results, the first value of Tuple is the result set, and the second value is the total number of rows (for example, There are 100 records in total, 10 per page, and the current first page, then the first value is 10 records, and the second value is 100)

In the sample project, I use two methods to achieve it Pagination:

1. The first one is based on 2 queries. The first query gets the total number, and the second query gets the result set.

2. The second one is based on 1 this query, using Offest/Fetch of SqlServer, so it only supports Sql Server 2012+, so you can choose different implementations according to the Sql Server version you use. Here is of course The second implementation is more efficient.

Run the example

1. After downloading or Clone the Github Repo locally, go to the Database directory and decompress Database.7z

2. Attach to Sql Server . By default, I use Sql Server LocalDB, and the connection string is Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=DapperPagingSample;integrated security=True; If you are not using LocalDB, please modify the connection string of App.Config as appropriate.

3. Ctrl+F5 runs the program. In the sample project, I used a simple WinForm program, but it should be able to better demonstrate the paging effect.

Multiple table support

Added examples to support multi-table query, for example, there are two Log tables, Level table, Log The LevelId field refers to the Level Id field. Through the following query, you can realize paging, sorting, and filtering of multi-table queries:

The first is an example of two queries (basically supports all versions of Sql Server):

public Tuple<IEnumerable<Log>, int> Find(LogSearchCriteria criteria
      , int pageIndex
      , int pageSize
      , string[] asc
      , string[] desc)
    {
      using (IDbConnection connection = base.OpenConnection())
      {
        const string countQuery = @"SELECT COUNT(1)
                      FROM   [Log] l
                      INNER JOIN [Level] lv ON l.LevelId = lv.Id
                      /**where**/";

        const string selectQuery = @" SELECT *
              FROM  ( SELECT  ROW_NUMBER() OVER ( /**orderby**/ ) AS RowNum, l.*, lv.Name as [Level]
                   FROM   [Log] l
                   INNER JOIN [Level] lv ON l.LevelId = lv.Id
                   /**where**/
                  ) AS RowConstrainedResult
              WHERE  RowNum >= (@PageIndex * @PageSize + 1 )
                AND RowNum <= (@PageIndex + 1) * @PageSize
              ORDER BY RowNum";

        SqlBuilder builder = new SqlBuilder();

        var count = builder.AddTemplate(countQuery);
        var selector = builder.AddTemplate(selectQuery, new { PageIndex = pageIndex, PageSize = pageSize });

        if (!string.IsNullOrEmpty(criteria.Level))
          builder.Where("lv.Name= @Level", new { Level = criteria.Level });

        if (!string.IsNullOrEmpty(criteria.Message))
        {
          var msg = "%" + criteria.Message + "%";
          builder.Where("l.Message Like @Message", new { Message = msg });
        }

        foreach (var a in asc)
        {
          if(!string.IsNullOrWhiteSpace(a))
            builder.OrderBy(a);
        }

        foreach (var d in desc)
        {
          if (!string.IsNullOrWhiteSpace(d))
            builder.OrderBy(d + " desc");
        }

        var totalCount = connection.Query<int>(count.RawSql, count.Parameters).Single();
        var rows = connection.Query<Log>(selector.RawSql, selector.Parameters);

        return new Tuple<IEnumerable<Log>, int>(rows, totalCount);
      }
    }
Copy after login

The second example is through Offset/Fetch query (supports Sql Server 2012+)

public Tuple<IEnumerable<Log>, int> FindWithOffsetFetch(LogSearchCriteria criteria
                        , int pageIndex
                        , int pageSize
                        , string[] asc
                        , string[] desc)
    {
      using (IDbConnection connection = base.OpenConnection())
      {
        
        const string selectQuery = @" ;WITH _data AS (
                      SELECT l.*, lv.Name AS [Level]
                      FROM   [Log] l
                      INNER JOIN [Level] lv ON l.LevelId = lv.Id
                      /**where**/
                    ),
                      _count AS (
                        SELECT COUNT(1) AS TotalCount FROM _data
                    )
                    SELECT * FROM _data CROSS APPLY _count /**orderby**/ OFFSET @PageIndex * @PageSize ROWS FETCH NEXT @PageSize ROWS ONLY";

        SqlBuilder builder = new SqlBuilder();
        
        var selector = builder.AddTemplate(selectQuery, new { PageIndex = pageIndex, PageSize = pageSize });

        if (!string.IsNullOrEmpty(criteria.Level))
          builder.Where("lv.Name = @Level", new { Level = criteria.Level });

        if (!string.IsNullOrEmpty(criteria.Message))
        {
          var msg = "%" + criteria.Message + "%";
          builder.Where("l.Message Like @Message", new { Message = msg });
        }
        
        foreach (var a in asc)
        {
          if (!string.IsNullOrWhiteSpace(a))
            builder.OrderBy(a);
        }

        foreach (var d in desc)
        {
          if (!string.IsNullOrWhiteSpace(d))
            builder.OrderBy(d + " desc");
        }
        
        var rows = connection.Query<Log>(selector.RawSql, selector.Parameters).ToList();

        if(rows.Count == 0)
          return new Tuple<IEnumerable<Log>, int>(rows, 0);
        

        return new Tuple<IEnumerable<Log>, int>(rows, rows[0].TotalCount);
        
      }
    }
Copy after login

The above is the detailed content of Tutorial on how to use Dapper to achieve paging effects. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Users encounter rare glitches: Samsung Watch smartwatches suddenly experience white screen issues Users encounter rare glitches: Samsung Watch smartwatches suddenly experience white screen issues Apr 03, 2024 am 08:13 AM

You may have encountered the problem of green lines appearing on the screen of your smartphone. Even if you have never seen it, you must have seen related pictures on the Internet. So, have you ever encountered a situation where the smart watch screen turns white? On April 2, CNMO learned from foreign media that a Reddit user shared a picture on the social platform, showing the screen of the Samsung Watch series smart watches turning white. The user wrote: "I was charging when I left, and when I came back, it was like this. I tried to restart, but the screen was still like this during the restart process." Samsung Watch smart watch screen turned white. The Reddit user did not specify the smart watch. Specific model. However, judging from the picture, it should be Samsung Watch5. Previously, another Reddit user also reported

Kyushu Fengshen Assassin 4S Radiator Review Air-cooled 'Assassin Master' Style Kyushu Fengshen Assassin 4S Radiator Review Air-cooled 'Assassin Master' Style Mar 28, 2024 am 11:11 AM

Speaking of ASSASSIN, I believe players will definitely think of the master assassins in "Assassin's Creed". They are not only skilled, but also have the creed of "devoting themselves to the darkness and serving the light". The ASSASSIN series of flagship air-cooled radiators from the appliance brand DeepCool coincide with each other. Recently, the latest product of this series, ASSASSIN4S, has been launched. "Assassin in Suit, Advanced" brings a new air-cooling experience to advanced players. The appearance is full of details. The Assassin 4S radiator adopts a double tower structure + a single fan built-in design. The outside is covered with a cube-shaped fairing, which has a strong overall sense. It is available in white and black colors to meet different colors. Tie

PHP development: How to implement table data sorting and paging functions PHP development: How to implement table data sorting and paging functions Sep 20, 2023 am 11:28 AM

PHP development: How to implement table data sorting and paging functions In web development, processing large amounts of data is a common task. For tables that need to display a large amount of data, it is usually necessary to implement data sorting and paging functions to provide a good user experience and optimize system performance. This article will introduce how to use PHP to implement the sorting and paging functions of table data, and give specific code examples. The sorting function implements the sorting function in the table, allowing users to sort in ascending or descending order according to different fields. The following is an implementation form

Exquisite light and shadow art in spring, Haqu H2 is the cost-effective choice Exquisite light and shadow art in spring, Haqu H2 is the cost-effective choice Apr 17, 2024 pm 05:07 PM

With the arrival of spring, everything revives and everything is full of vitality and vitality. In this beautiful season, how to add a touch of color to your home life? Haqu H2 projector, with its exquisite design and super cost-effectiveness, has become an indispensable beauty in this spring. This H2 projector is compact yet stylish. Whether placed on the TV cabinet in the living room or next to the bedside table in the bedroom, it can become a beautiful landscape. Its body is made of milky white matte texture. This design not only makes the projector look more advanced, but also increases the comfort of the touch. The beige leather-like material adds a touch of warmth and elegance to the overall appearance. This combination of colors and materials not only conforms to the aesthetic trend of modern homes, but also can be integrated into

Huntkey MX750P full module power supply review: 750W of concentrated platinum strength Huntkey MX750P full module power supply review: 750W of concentrated platinum strength Mar 28, 2024 pm 03:20 PM

With its compact size, the ITX platform has attracted many players who pursue the ultimate and unique beauty. With the improvement of manufacturing processes and technological advancements, both Intel's 14th generation Core and RTX40 series graphics cards can exert their strength on the ITX platform, and gamers also There are higher requirements for SFX power supply. Game enthusiast Huntkey has launched a new MX series power supply. In the ITX platform that meets high-performance requirements, the MX750P full-module power supply has a rated power of up to 750W and has passed 80PLUS platinum level certification. Below we bring the evaluation of this power supply. Huntkey MX750P full-module power supply adopts a simple and fashionable design concept. There are two black and white models for players to choose from. Both use matte surface treatment and have a good texture with silver gray and red fonts.

Colorful Hidden Star P15 24 Review: A hard-core all-round gaming laptop with both good looks and performance Colorful Hidden Star P15 24 Review: A hard-core all-round gaming laptop with both good looks and performance Mar 06, 2024 pm 04:40 PM

In the current era of rapid technological development, laptops have become an indispensable and important tool in people's daily life and work. For those players who have high performance requirements, a laptop with powerful configuration and excellent performance can meet their hard-core needs. With its excellent performance and stunning design, the Colorful Hidden Star P15 notebook computer has become the leader of the future and can be called a model of hard-core notebooks. Colorful Hidden Star P1524 is equipped with a 13th generation Intel Core i7 processor and RTX4060Laptop GPU. It adopts a more fashionable spaceship design style and has excellent performance in details. Let us first take a look at the features of this notebook. Supreme equipped with Intel Core i7-13620H processing

Easily understand 4K HD images! This large multi-modal model automatically analyzes the content of web posters, making it very convenient for workers. Easily understand 4K HD images! This large multi-modal model automatically analyzes the content of web posters, making it very convenient for workers. Apr 23, 2024 am 08:04 AM

A large model that can automatically analyze the content of PDFs, web pages, posters, and Excel charts is not too convenient for workers. The InternLM-XComposer2-4KHD (abbreviated as IXC2-4KHD) model proposed by Shanghai AILab, the Chinese University of Hong Kong and other research institutions makes this a reality. Compared with other multi-modal large models that have a resolution limit of no more than 1500x1500, this work increases the maximum input image of multi-modal large models to more than 4K (3840x1600) resolution, and supports any aspect ratio and 336 pixels to 4K Dynamic resolution changes. Three days after its release, the model topped the HuggingFace visual question answering model popularity list. Easy to handle

How to use JavaScript to implement table paging function? How to use JavaScript to implement table paging function? Oct 20, 2023 pm 06:19 PM

How to use JavaScript to implement table paging function? With the development of the Internet, more and more websites use tables to display data. In some cases where the amount of data is large, the data needs to be displayed in pages to improve user experience. This article will introduce how to use JavaScript to implement table paging function and provide specific code examples. 1. HTML structure First, we need to prepare an HTML structure to host tables and paging buttons. We can use &lt;tab

See all articles