ctrlShiftBryan
ctrlShiftBryan

Reputation: 27760

How can you use a LINQ Lambda Where Property Count = Something

I have an Entity object, Item, that looks like this..

public class Item()
{
    IEnumerable<Category> Categories { get; set; }
}

and I am trying to get a list of items that have a 0 count

var unassigned = db.Items.Where(i => i.Categories.Count() == 0);

or

var unassigned = db.Items.Where(i => i.Categories.Any());

but both throw the error... "The specified type member 'Categories' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported."

What is this error telling me and how can I query for what I am looking for?

Upvotes: 1

Views: 423

Answers (2)

Lav
Lav

Reputation: 1896

Try

var unassigned = db.Items.Categories.Where(c=>c.Count() ==0);

Upvotes: 0

Matt Greer
Matt Greer

Reputation: 62057

Is Category an entity as well that is tracked by EF? EF doesn't seem to think it is. Are you using POCOs? Typically navigation properties that are 1-to-many need to be represented with ICollection<T> not IEnumerable.

Basically EF is saying it doesn't know how to turn db.Items.Where(i => i.Categories.Count() == 0) into SQL, because it's unsure what Categories is in relation to the database.

It's also possible you will need to Include("Categories") on the EF call, but I think you have more fundamental problems than this.

Upvotes: 2

Related Questions