简体   繁体   中英

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

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;

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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