-
Notifications
You must be signed in to change notification settings - Fork 1
/
QueryablePaginatedExtensions.cs
75 lines (67 loc) · 3.01 KB
/
QueryablePaginatedExtensions.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Alamut.Data.NoSql;
using Microsoft.EntityFrameworkCore;
namespace Alamut.Data.Paging
{
public static class QueryablePaginatedExtensions
{
/// <summary>
/// Gets the paginated data.
/// </summary>
/// <typeparam name="T"> </typeparam>
/// <param name="query"> The query. </param>
/// <param name="startIndex"> Start index of the row. </param>
/// <param name="itemCount"> Size of the page. </param>
/// <returns> </returns>
public static IQueryable<T> ToPage<T>(this IQueryable<T> query, int startIndex, int itemCount)
{
if (startIndex < 0)
startIndex = 0;
return query.Skip(startIndex).Take(itemCount);
}
public static IQueryable<T> ToPage<T>(this IQueryable<T> query, IPaginatedCriteria criteria)
{
return query.ToPage(criteria.StartIndex, criteria.PageSize);
}
/// <summary>
/// Creates an <see cref="IPaginated{T}" /> instance from the specified query.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="query">The query.</param>
/// <param name="paginatedCriteria">The paginated criteria.</param>
/// <returns></returns>
public static IPaginated<T> ToPaginated<T>(this IQueryable<T> query, IPaginatedCriteria paginatedCriteria)
{
return new Paginated<T>(
query.ToPage(paginatedCriteria.StartIndex, paginatedCriteria.PageSize).ToList(),
query.Count(),
paginatedCriteria.CurrentPage,
paginatedCriteria.PageSize);
}
/// <summary>
/// Creates an <see cref="IPaginated{T}" /> instance from the specified query.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="query">The query.</param>
/// <param name="paginatedCriteria">The paginated criteria.</param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public static async Task<IPaginated<T>> ToPaginatedAsync<T>(this IQueryable<T> query,
IPaginatedCriteria paginatedCriteria, CancellationToken cancellationToken = default)
{
var data = await query.ToPage(paginatedCriteria)
.ToListAsync(cancellationToken);
var count = await query.CountAsync(cancellationToken);
// await Task.WhenAll(dataTask, countTask);
// "A second operation started on this context before a previous operation completed. This is usually caused by different threads using the same instance of DbContext. For more information on how to avoid threading issues with DbContext, see https://go.microsoft.com/fwlink/?linkid=2097913.
return new Paginated<T>(
data,
count,
paginatedCriteria.CurrentPage,
paginatedCriteria.PageSize);
}
}
}