How to use linq to entities queries or Lists in linq to sql queries

How to use linq to entities queries or Lists in linq to sql queries,linq,entity-framework,linq-to-sql,lambda,linq-to-entities,Linq,Entity Framework,Linq To Sql,Lambda,Linq To Entities,I have a generic EF repository and need to get items from database using nested where statements. var categoryGroups = repository.Categories.Where(a => a.Vehicles.Where(v => bodyTypesFilter.Any(b => b == v.BodyType)).Count() > 0); I include only the important part of lambda expression. Here bodyTypesFilter is a List and I'm getting following exception. Unable to create a null constant value of type 'System.Collections.Generic.List`1'. Only entity types, enumer

I have a generic EF repository and need to get items from database using nested where statements.

var categoryGroups = repository.Categories.Where(a => a.Vehicles.Where(v => 
                   bodyTypesFilter.Any(b => b == v.BodyType)).Count() > 0);

I include only the important part of lambda expression. Here bodyTypesFilter is a List and I'm getting following exception.

Unable to create a null constant value of type 'System.Collections.Generic.List`1'. Only entity types, enumeration types or primitive types are supported in this context.

I understand that it's due to I'm trying to generate linq to sql query which includes List and it isn't allowed. But I don't know how to avoid it or overcome.

Please help to find out a solution.


#1

It's about the part

bodyTypesFilter.Any(b => b == v.BodyType)

You can't compare objects in EF queries, because the part bodyTypesFilter can't be translated into SQL. Do this in stead:

bodyTypesFilterIds.Contains(v.BodyType.Id)

(or probably v.BodyTypeId)

where bodyTypesFilterIds is a list of Id values in stead of objects.

(Not Any, because that creates a monster query that easily develops into a too deep nesting level).


#2

are any of the elements of bodyTypesFilter null?

#3

explain what do you want to get as result.

#4

Yes @Ben it's null when throwing exception

#5

I want to get those items for which vehicles bodyType is contained in bodyTypesFilter List

#6

Check out this link: stackoverflow.com/questions/12284497/…