简体   繁体   English

即使查询返回 IQueryable,CountAsync() 也不起作用<t> ?</t>

[英]CountAsync() does not work even if the query returns an IQueryable<T>?

I have a query in c#:我在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:检查它返回的查询:

图片

RegistrationDateGrouppedViewModel.cs : 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 :分页扩展.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 .但在变量result内部,特别是CountAsync()方法返回null

Why even if i give him the correct type is not counting my result○6 and returns null ?为什么即使我给他正确的类型也不计算我的result○6并返回null

Can anyone help me on this one?谁能帮我解决这个问题?

UPDATE更新

PageResult.cs :页面结果.cs

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

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!在计算之前,我必须使用.ToList()使查询成为一个列表,现在分页按预期工作! Thanks @simplygood for providing help感谢@simplygood 提供帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM