Search code examples
c#.netlinq

Cannot convert expression type 'System.Linq.IQueryable to return type 'System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable


I'm trying to join 2 tables and return data that meet a specific condition. However, I get this error instead

Cannot convert expression type 'System.Linq.IQueryable<TicketBooking.Data.DataModel.Flight>' to return type 'System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<TicketBooking.Data.DataModel.Flight>>'

Here is the red squiggle error code, my intention is to return the flight that has the specific date.

public async Task<IEnumerable<Flight>> GetFlightByDate(DateTime date)
    {
        var query = from f in _context.Flights
            join fs in _context.FlightSchedules
                on f.ScheduleId equals fs.Id
                    where fs.DepartureTime == date
            select new 
            {
                flight = f
            };

        return query;
    }

Solution

  • You need .ToListAsync() to execute the query.

    While you have modify your query as your current query return list of anonymous type but not list of Flight.

    public async Task<IEnumerable<Flight>> GetFlightByDate(DateTime date)
    {
        var query = from f in _context.Flights
            join fs in _context.FlightSchedules
                on f.ScheduleId equals fs.Id
            where fs.DepartureTime == date
            select f;
    
        return await query.ToListAsync();
    }