Home > Software engineering >  .Net 7 Minimal API - using .Where causing error
.Net 7 Minimal API - using .Where causing error

Time:12-18

I am doing some learning on .Net 7 and minimal API's

I am simply trying to return a list of all timesheets within a payperiod. but I get the following error

Error CS1061 'Task<List>' does not contain a definition for 'Where' and no accessible extension method 'Where' accepting a first argument of type 'Task<List>' could be found (are you missing a using directive or an assembly reference?)

group.MapGet("/Payperiod/{payperiod}", async Task<Results<Ok<Timesheet>, NotFound>> (string payperiod, TimesheetAPIContext db) =>
    {
        return await db.Timesheet.ToListAsync().Where(t => t.Contains(payperiod))
            is Timesheet model
                ? TypedResults.Ok(model)
                : TypedResults.NotFound();
    })
    .WithName("GetTimesheetByPayPeriod")
    .WithOpenApi();

Can someone help me understand what is going on here and how I should be writing this endpoint?

Cheers

CodePudding user response:

You can't use .Where on a Task you need to first call .Result to actually get a List.

return await db.Timesheet.ToListAsync().Result.Where(t => t.Contains(payperiod))
            is Timesheet model
                ? TypedResults.Ok(model)
                : TypedResults.NotFound();

CodePudding user response:

First, you should put the where() before ToListAsync(), simply, you can think all linq's meothd end with Async is final method, you should not chain invoke after it. Second, you can not use the Is Timesheet to check where it is empty. you should use the Any(). the modifed code as below:

group.MapGet("/Payperiod/{payperiod}", async Task<Results<Ok<Timesheet>, NotFound>> (string payperiod, TimesheetAPIContext db) =>
    {
        var ret = await db.Timesheet.Where(t => t.Contains(payperiod)).ToListAsync();
        
        return ret.Any() 
                ? TypedResults.Ok(model)
                : TypedResults.NotFound();
    })
    .WithName("GetTimesheetByPayPeriod")
    .WithOpenApi();
  • Related