分页后对 UserManager<T> 进行额外的异步调用

Make additional asynchronous call to UserManager<T> after pagination

我有一个 LINQ 查询,它通过过滤和分页从数据库中获取结果并将结果映射到 PaginatedList<T>

var bookReservationList = await _dbContext.BookReservations
    .Include(x => x.Books).Select(
    book => new BookRequestViewModel
    {

        Author = book.Books.Author

    }).PaginatedListAsync(pageNumber, pageSize);

现在有了从上面 LINQ 查询中的 bookReservationList 获得的结果,我想调用 GetUserEmailAsync 来获得

Requester = await _identityService.GetUserEmailAsync(book.RequesterId),也就是对UserManager<T>

的调用

我一直在尝试这种方式,但我失败了: 将结果映射到 Task

    var res = bookReservationList.Items.Select(async y => new BookRequestViewModel
    {
        Requester = await _identityService.GetUserEmailAsync(y.RequesterId);

    });

PaginatedListAsync

public static Task<PaginatedList<TDestination>> PaginatedListAsync<TDestination>(this IQueryable<TDestination> queryable, int pageNumber, int pageSize)
{
    return PaginatedList<TDestination>.CreateAsync(queryable, pageNumber, pageSize);
}

分页列表

public class PaginatedList<T>
{
    public List<T> Items { get; }
    public int PageIndex { get; }
    public int TotalPages { get; }
    public int TotalCount { get; }

    public PaginatedList(List<T> items, int count, int pageIndex, int pageSize)
    {
        PageIndex = pageIndex;
        TotalPages = (int)Math.Ceiling(count / (double)pageSize);
        TotalCount = count;
        Items = items;
    }

    public bool HasPreviousPage => PageIndex > 1;

    public bool HasNextPage => PageIndex < TotalPages;

    public static async Task<PaginatedList<T>> CreateAsync(IQueryable<T> source, int pageIndex, int pageSize)
    {
        var count = await source.CountAsync();
        var items = await source.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToListAsync();

        return new PaginatedList<T>(items, count, pageIndex, pageSize);
    }
}

GetUserEmailAsync 的实现如下:

public interface IIdentityService
{
    Task<string> GetUserEmailAsync(string userId);
}

ViewModel

public class BookRequestViewModel
{
    public int Id { get; set; }
    public string Requester { get; set; }
    public string RequesterId { get; set; }
    public DateTime RequestDate { get; set; }
}

基本上,我想return结果为

Task<PaginatedList<BookRequestViewModel>> GetRequestedBookList(int pageNumber, int pageSize);但是没有这样做。

LINQ 无法做到这一点。你必须使用 foreach

foreach (y in bookReservationList.Items)
{
    y.Requester = await _identityService.GetUserEmailAsync(y.RequesterId);
}