LINQ ToListAsync expression with a DbSet

user3736648 picture user3736648 · Aug 7, 2014 · Viewed 27.8k times · Source

I have coded a C# MVC5 Internet application, and have a question about using the .ToListAsync LINQ expression.

Here is my code that works in an Index action result:

IEnumerable<IMapLocationItem> mapLocationImageGalleries = await db.mapLocationImageGalleries.Where(m => m.userName.Equals(userName)).ToListAsync();
IEnumerable<IMapLocationItem> mapLocationVideoGalleries = await db.mapLocationVideoGalleries.Where(m => m.userName.Equals(userName)).ToListAsync();
IEnumerable<IMapLocationItem> mapLocationItemsCombined = mapLocationImageGalleries.Concat(mapLocationVideoGalleries);

I am wanting to create a service function for the above code. Here is what I have coded:

public async Task<IEnumerable<IMapLocationItem>> GetAllMapLocationItemsFromUserName(string userName)
{
    IEnumerable<IMapLocationItem> mapLocationImageGalleries = await db.mapLocationImageGalleries.Where(m => m.userName.Equals(userName)).ToListAsync();
    IEnumerable<IMapLocationItem> mapLocationVideoGalleries = await db.mapLocationVideoGalleries.Where(m => m.userName.Equals(userName)).ToListAsync();
    IEnumerable<IMapLocationItem> mapLocationItemsCombined = mapLocationImageGalleries.Concat(mapLocationVideoGalleries);
    return mapLocationItemsCombined;
}

I am getting the following error:

Error   17  'System.Linq.IQueryable<CanFindLocation.Models.MapLocationItems.MapLocationImageGallery>' does not contain a definition for 'ToListAsync' and no extension method 'ToListAsync' accepting a first argument of type 'System.Linq.IQueryable<CanFindLocation.Models.MapLocationItems.MapLocationImageGallery>' could be found (are you missing a using directive or an assembly reference?)

The exact same code works fine in the Index action result, yet not in a service method. Why is this and how can I get this working?

Thanks in advance

Answer

Yuval Itzchakov picture Yuval Itzchakov · Aug 7, 2014

As noted in the comments, add using System.Data.Entity (under the Entity Framework package) to get the QueryableExtensions.

For .NET Core, these methods are under Microsoft.EntityFrameworkCore