Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.ToListAsync() not found when using WhereIf

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?)

like image 739
Mahmut Gundogdu Avatar asked Dec 23 '22 07:12

Mahmut Gundogdu


2 Answers

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;

like image 136
Xeevis Avatar answered Dec 29 '22 06:12

Xeevis


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.

like image 27
Camilo Terevinto Avatar answered Dec 29 '22 06:12

Camilo Terevinto