RSolberg
RSolberg

Reputation: 26972

EF LINQ many to one filter/where

I'm getting an exception when the GetProducts() method is called below. I'm essentially trying to filter down my list of Products by what is available in the specified Country. There is a one to many relationship setup between a Product and a Country.

    public static List<Product> GetProducts(Country country)
    {
        Context db = new Context();
        return db.Products.Where(m => m.Countries.Contains(country)).ToList<Product>();
    }

Unable to create a constant value of type 'DataModels.Country'. Only primitive types or enumeration types are supported in this context.

If I'm not going about this the right way, what is the best way to filter Products by the single selected Country?

Upvotes: 1

Views: 789

Answers (1)

Aducci
Aducci

Reputation: 26644

You can only compare based on primitive types.

I would change it to use the Any method. Replace ID with the Country entity key (or a unique property)

db.Products.Where(m => m.Countries.Any(c => c.ID == country.ID)).ToList<Product>();

Upvotes: 3

Related Questions