Search code examples
c#asynchronousentity-framework-coreef-core-2.0

EfCore ToListAsync() Throw exception with where condition


I have a problem with an async task that get items from the database with a specific condition When i call the ToListAsync() i get this error

Expression of type 'System.Collections.Generic.IAsyncEnumerable1[System.Guid]' cannot be used for constructor parameter of type 'System.Collections.Generic.IEnumerable1[System.Guid]' Parameter name: arguments[0]

This is the code snippet:

public async Task<IEnumerable<Parent>> GetItems(List<Guid> TypeIds)
{
    var items = context.Parent.Include(x => x.Child).Where(x => new HashSet<Guid>(x.Child.Select(y => y.TypeId).Distinct()).SetEquals(new HashSet<Guid>(TypeIds)));
    return await items.Include(x=> x.Child).ToListAsync();
}

If I implement this method not async I won't get the error and all works.


Solution

  • You can't have a Where lambda like that for Entity Framework, remember that the expression is going to get converted to SQL which has no idea what a HashSet is. You are probably looking for something like this instead:

    var items = context.Parent
        .Include(x => x.Child)
        .Where(x => x.Child.Any(y => TypeIds.Contains(y.TypeId)));