2021年2月7日星期日

Make additional asynchronous call to database after pagination

I have a LINQ query that gets the results from a database with filtering and pagination and that maps the result to the PaginatedList<T>.

var bookReservationList = await _dbContext.BookReservations      .Include(x => x.Books).Select(      book => new BookRequestViewModel      {            Author = book.Books.Author        }).PaginatedListAsync(pageNumber, pageSize);  

Now with the result obtained from the bookReservationList in the above LINQ query, I wanted to call the GetUserEmailAsync to get the Requester as await _identityService.GetUserEmailAsync(book.RequesterId)

I have been trying in this way but I am failing:

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

PaginatedList

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

The implementation of GetUserEmailAsync is done as:

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

Basically, I want to return the result as

Task<PaginatedList<BookRequestViewModel>> GetRequestedBookList(int pageNumber, int pageSize); but failing to do so.

https://stackoverflow.com/questions/66095413/make-additional-asynchronous-call-to-database-after-pagination February 08, 2021 at 11:03AM

没有评论:

发表评论