2

in my repository I have a method "AllMakesAsync" that retrieves vehicle makes from database:

public async Task<IEnumerable<VehicleMake>> AllMakesAsync()
    {
        return await _context.VehicleMakes.ToListAsync();
    }

In repository I also have "GetVehicleMakesWithPaginationAsync" method in which "AllMakesAsync" method is used:

  public async Task<IEnumerable<VehicleMake>> GetVehicleMakesWithPaginationAsync(string search, int? page, string sort)
    {
        var makes = await AllMakesAsync();

        switch (sort)
        {
            case "Name desc":
                makes = makes.OrderByDescending(x => x.Name);
                break;
            default:
                makes = makes.OrderBy(x => x.Name);
                break;
        }

        if (search == null)
        {
            return makes.ToList().ToPagedList(page ?? 1, 5);
        }

        return makes.Where(x => x.Name.StartsWith(search, StringComparison.OrdinalIgnoreCase)).ToList().ToPagedList(page ?? 1, 5);
    }

I was told that I should not use "ToListAsync()" if I'm gonna use filtering on dataset and that I should use "AsQueryable" instead.

The problem is that I don't know how to implement "AsQueryable" asynchronously.

I can return "AsQueryable" like this:

    public async Task<IQueryable<VehicleMake>> AllMakesAsync()
    {
        var vehicleMakes = await _context.VehicleMakes.AsQueryable().ToListAsync();
        return vehicleMakes.AsQueryable();
    }

but here I use "ToListAsync()" again so it's not good.

Can someone please explain me how to do this properly.

iantukic
  • 87
  • 2
  • 13

1 Answers1

4

You're executing your query, and then after you've already finished executing it and getting your results back, you then try to define what the query should be, what items should be in it, what order, etc. You need to not do that. You need to determine what your query is (determining what filters should be there, what orderings, the page size, etc.) and then execute your query by calling ToListAsync.

Trying to execute the query, get the results back, but then try to pretend that those already returned results are in fact a not-yet-executed query doesn't actually do anything to ensure that you define your query before you execute it.

Servy
  • 202,030
  • 26
  • 332
  • 449