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);
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); } }
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); } }
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!

Design patterns in C#.NET include Singleton patterns and dependency injection. 1.Singleton mode ensures that there is only one instance of the class, which is suitable for scenarios where global access points are required, but attention should be paid to thread safety and abuse issues. 2. Dependency injection improves code flexibility and testability by injecting dependencies. It is often used for constructor injection, but it is necessary to avoid excessive use to increase complexity.

C#.NET is widely used in the modern world in the fields of game development, financial services, the Internet of Things and cloud computing. 1) In game development, use C# to program through the Unity engine. 2) In the field of financial services, C#.NET is used to develop high-performance trading systems and data analysis tools. 3) In terms of IoT and cloud computing, C#.NET provides support through Azure services to develop device control logic and data processing.

.NETFrameworkisWindows-centric,while.NETCore/5/6supportscross-platformdevelopment.1).NETFramework,since2002,isidealforWindowsapplicationsbutlimitedincross-platformcapabilities.2).NETCore,from2016,anditsevolutions(.NET5/6)offerbetterperformance,cross-

The C#.NET developer community provides rich resources and support, including: 1. Microsoft's official documents, 2. Community forums such as StackOverflow and Reddit, and 3. Open source projects on GitHub. These resources help developers improve their programming skills from basic learning to advanced applications.

The advantages of C#.NET include: 1) Language features, such as asynchronous programming simplifies development; 2) Performance and reliability, improving efficiency through JIT compilation and garbage collection mechanisms; 3) Cross-platform support, .NETCore expands application scenarios; 4) A wide range of practical applications, with outstanding performance from the Web to desktop and game development.

C# is not always tied to .NET. 1) C# can run in the Mono runtime environment and is suitable for Linux and macOS. 2) In the Unity game engine, C# is used for scripting and does not rely on the .NET framework. 3) C# can also be used for embedded system development, such as .NETMicroFramework.

C# plays a core role in the .NET ecosystem and is the preferred language for developers. 1) C# provides efficient and easy-to-use programming methods, combining the advantages of C, C and Java. 2) Execute through .NET runtime (CLR) to ensure efficient cross-platform operation. 3) C# supports basic to advanced usage, such as LINQ and asynchronous programming. 4) Optimization and best practices include using StringBuilder and asynchronous programming to improve performance and maintainability.

C# is a programming language released by Microsoft in 2000, aiming to combine the power of C and the simplicity of Java. 1.C# is a type-safe, object-oriented programming language that supports encapsulation, inheritance and polymorphism. 2. The compilation process of C# converts the code into an intermediate language (IL), and then compiles it into machine code execution in the .NET runtime environment (CLR). 3. The basic usage of C# includes variable declarations, control flows and function definitions, while advanced usages cover asynchronous programming, LINQ and delegates, etc. 4. Common errors include type mismatch and null reference exceptions, which can be debugged through debugger, exception handling and logging. 5. Performance optimization suggestions include the use of LINQ, asynchronous programming, and improving code readability.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Atom editor mac version download
The most popular open source editor

SublimeText3 Mac version
God-level code editing software (SublimeText3)

SublimeText3 Chinese version
Chinese version, very easy to use
