Home > other >  CountAsync() does not work even if the query returns an IQueryable<T>?
CountAsync() does not work even if the query returns an IQueryable<T>?

Time:10-01

I have a query in c#:

var queryResult = query.Include(x => x.Activity).Include(x => x.Commission).Include(x => x.People)
  .GroupBy(x => new { x.PeopleId, x.DateReference })
  .Select(x => new RegistrationDateGrouppedViewModel()
    {
       DateReference = x.Key.DateReference,
       PeopleId = x.Key.PeopleId,
       MinuteWorkedSum = x.ToList().Sum(min => min.MinuteWorked),
       RegistrationList = x.ToList().ToRegistrationViewModel().ToList()
    }); // the type of this query is IQueryable<RegistrationDateGrouppedViewModel> 

Inspecting the query it returns this:

image

RegistrationDateGrouppedViewModel.cs:

public class RegistrationDateGrouppedViewModel
{
  public DateTime DateReference { get; set; }
  public Guid PeopleId { get; set; }
  public int MinuteWorkedSum { get; set; }
  public List<RegistrationViewModel> RegistrationList { get; set; }
}

I want to enable pagination on my query so i added it:

var result = new PageResult<RegistrationDateGrouppedViewModel>()
{
  CollectionSize = await queryResult.CountAsync(), // this is of type int
  Result = queryResult.Paginate(page, size).ToList() //this is of type List<T>
};

This is the pagination method:

PagingExtension.cs:

public static IQueryable<TSource> Paginate<TSource>(this IQueryable<TSource> data, int page, int size)
{
   if (page > 0 && size > 0)
   {
      return data.Skip((page - 1) * size).Take(size);
   }
   return data;
}

But inside the variable result particularly the CountAsync() method returns null.

Why even if i give him the correct type is not counting my result○6 and returns null?

Can anyone help me on this one?

UPDATE

PageResult.cs:

public class PageResult<T>
{
   public List<T> Result { get; set; }
   public int CollectionSize { get; set; }
}

CodePudding user response:

Well it turns out that i just needed to add this:

var result = new PageResult<RegistrationDateGrouppedViewModel>()
{
   CollectionSize = queryResult.ToList().Count(), // added ToList() here
   Result = queryResult.Paginate(page, size).ToList()
};

Before counting i had to make the query a list using .ToList() and now pagination works as expected! Thanks @simplygood for providing help

  • Related