6

I am reading this tutorial. I want to use async query with EF Core.

It works well when i use like this:

var tasks = await _taskRepository
    .GetAll()
    //.WhereIf(!string.IsNullOrEmpty(input?.Title), x => x.Title.Contains(input.Title))
    //.WhereIf(input?.State != null, x => x.State == input.State.Value)
    //.OrderByDescending(x => x.CreationTime)
    .ToListAsync();

but i want to use whereif and orderby like

var tasks = await _taskRepository
    .GetAll()
    .WhereIf(!string.IsNullOrEmpty(input?.Title), x => x.Title.Contains(input.Title))
    .WhereIf(input?.State != null, x => x.State == input.State.Value)
    .OrderByDescending(x => x.CreationTime)
    .ToListAsync();

Error:

'IOrderedEnumerable' does not contain a definition for 'ToListAsync' and no extension method 'ToListAsync' accepting a first argument of type 'IOrderedEnumerable' could be found (are you missing a using directive or an assembly reference?)

Xeevis
  • 4,325
  • 25
  • 26
Mahmut Gundogdu
  • 543
  • 4
  • 12

2 Answers2

8

You are using wrong WhereIf extension, it's easy to miss because you need to add extra using Visual Studio won't offer.

You are using extension which returns IEnumerable

Abp.Collections.Extensions.EnumerableExtensions.WhereIf<T>()

You need to use extension that returns IQueryable

Abp.Linq.Extensions.QueryableExtensions.WhereIf<T>()

It's an easy fix, just add at the top of the file using Abp.Linq.Extensions;

Xeevis
  • 4,325
  • 25
  • 26
2

IOrderedEnumerable<Task> means that you are working with a IEnumerable<Task>.

Entity Framework Core works with IQueryable<T> (which represents a database query), not IEnumerable<T> (which represents an in-memory collection). As soon as the IQueryable<T> is converted to a IEnumerable<T>, the query is executed on the database server and the result retrieved.

So: if you are calling a method that returns IEnumerable<T>, that method was not made to be used in LINQ to Entities.

Camilo Terevinto
  • 31,141
  • 6
  • 88
  • 120