0

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.

5
  • are any of the elements of bodyTypesFilter null?
    – Ben Reich
    May 29, 2013 at 17:43
  • explain what do you want to get as result.
    – Nick
    May 29, 2013 at 17:43
  • Yes @Ben it's null when throwing exception
    – Gohar
    May 29, 2013 at 18:43
  • I want to get those items for which vehicles bodyType is contained in bodyTypesFilter List
    – Gohar
    May 29, 2013 at 18:44
  • Check out this link: stackoverflow.com/questions/12284497/…
    – Ben Reich
    May 29, 2013 at 18:46

1 Answer 1

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).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.