Lücks
Lücks

Reputation: 3994

Entity framework LINQ where attribute equals of ICollection

I have a class "A" that contains a ICollection of "B". I want to select "A" including all "B" that the status equals "active". I'm trying this, but it's not working, it's returning inactive records of B:

        return MyContext.A
              .Where(t => t.B.Any(b => b.Status.Equals("active")))
              .Include(b => b.B);

I already tried adding this:

Where(b => b.B.Select(x => x.Status).Equals("active")) 

but I get an exception "cannot compare elements of type ienumerable"

Upvotes: 0

Views: 154

Answers (1)

MarcinJuraszek
MarcinJuraszek

Reputation: 125650

You can't Include navigation property items that match given predicate. Include always includes the entire collection.

You'd have to query your data into a separate class or anonymous item:

var results = context.A.Select(a => new { A = a, B = a.B.Where(b => b.Status == "Actuve") });

Upvotes: 1

Related Questions