Home > Blockchain >  LINQ question in .NET 6 / EF Core conversion
LINQ question in .NET 6 / EF Core conversion

Time:11-22

I currently have a .NET 4 Web API using Entity Framework 3 that I'm upgrading to .NET 6 / EF Core. I currently have a LINQ query that looks like this (and works fine):

[HttpGet]
public async Task<ActionResults> GetCars()
{
    var x = from f in _context.CarMakes
            group c in f.Make into m
            select new { c.Key };

    return Json(new 
                {   
                    data = await x.ToListAsync()
                };
}

This returns the following data:

Chevy
Ford
Volvo
Toyota

and so on.

I'm trying to use this same query in an ASP.NET Core 6 Web API that is using EF Core, but it fails, and throws an error.

In the .NET 6 / EF Core project, I have:

[HttpGet]
public async Task<ActionResults<IEnumerable<CarMakes>>>> GetCars()
{
    var x = from f in _context.CarMakes
            group c in f.Make into m
            select new { c.Key };

    return await x.ToListAsync();
}

I get an error message of:

Cannot implicity convert type 'System.Threading.Task.Task<System.Collections.GenericList

CodePudding user response:

I was getting this error while I'm unit testing Ef core.

Try this extension method:

    public static Task<List<TSource>> ToListAsyncSafe<TSource>(this IQueryable<TSource> source)
    {
        if (source == null)
            throw new ArgumentNullException(nameof(source));
        if (source is IAsyncEnumerable<TSource>)
            return source.ToListAsync();
        else
            return Task.FromResult(source.ToList());
    }

CodePudding user response:

Don't return an ActionResult, just return the IEnumerable.

CodePudding user response:

I got this working

[HttpGet]
public async Task<ActionResults<IEnumerable<CarMakes>>>> GetCars()
{
   var x = from f in _context.CarMakes
   group c in f.Make into m
   select new { c.Key };

  return Ok(await x.ToListAsync());

}

not 100% sure adding OK() gave me results, but it works for now.

  • Related