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

    Question

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

    var categoryGroups = repository.Categories(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.

    Wednesday, May 29, 2013 5:44 PM

Answers

  • Hi Gohar;

    What technology are you using, Entity Framework or Linq to SQL?

    Please show the schema of the tables involved in the query.

    On the exception you are getting please also include the inner exception, that one is generally more descriptive of the error.

    If you are using Linq to SQL try this query out as long as bodyTypesFilter and v.BodyType are of the same data type.

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


    Fernando (MCSD)

    If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".

    NOTE: If I ask for code, please provide something that I can drop directly into a project and run (including XAML), or an actual application project. I'm trying to help a lot of people, so I don't have time to figure out weird snippets with undefined objects and unknown namespaces.

    Wednesday, May 29, 2013 9:22 PM