Search code examples
c#linqentity-framework-4

Unable to convert IEnumerable<int> to List<T> in Entity Framework


I have a query like this

IEnumerable<int> companies = Employers
                             .Where(p => p.Id == User.ID
                             .SelectMany(p => p.companies)
                             .Select(p => p.Id);


return Employers
       .Where(p => companies.Contains(p.Companies)
       .Include(p => p.FirstName)
       .ToList();      

Here p.Companies refers to

Public Virtual List<Company>

under the class Employers.

This error occurs:

'IEnumerable' does not contain a definition for 'Contains' and the best extension method overload 'Queryable.Contains>(IQueryable>,List)' requires a receiver of type 'IQueryable>'


Solution

  • Doing this:

    Where(p => companies.Contains(p.Companies)
    

    you try to check if companies (IEnumerable<int> from previous query) contains some companies (object), not int value.

    You can't check if collection of int values contains some value which is not int(Company is some object).

    If you want to query all employers which have company with Id that is in companies variable use this Linq query:

    return Employers
           .Where(p => p.Companies.Any(c => companies.Contains(c.Id)))
           .Include(p => p.FirstName)
           .ToList();