Friday, April 29, 2011

How do I search the collection of a collection in my LINQ Where clause?

I've got the following ADO.NET Entity Framework Entity Data Model:

ADO.NET Entity Data Model

I want to find all the Policyholders with both a Service of a given Id and also a Keyword of a given Status.

This LINQ Does Not Work:

Dim ServicesId As Integer = ...
Dim KeywordStatus As Integer = ...

Dim FoundPolicyholders = From p As Policyholder In db.PolicyholderSet.Include("Keywords").Include("Services") _
                         Where p.Services.Id = ServicesId _
                         And p.Keywords.Status = KeywordStatus _
                         Select p

The Where clause cannot search the p.Services and p.Keywords EntityCollections in that way.

'Id' is not a member of 'System.Data.Objects.DataClasses.EntityCollection(Of ....Service)'.

What is the correct LINQ syntax to do what I want?

From stackoverflow
  • db.PolicyholderSet.Where(ph =>
       ph.Services.Any(s => s.Id == someId) &&
       ph.Keywords.Any(kw => kw.Status == someStatus))
    

    Why does your query not work? Because p.Services and p.Keywords are a Service and a Keyword collection - they have not property Id or Status hence you cannot use p.Services.Id or p.Keywords.Status.

    Visual Basic…

    Dim FoundPolicyholders = From p As Policyholder In db.PolicyholderSet.Include("Keywords").Include("Services") _
                             Where p.Services.Any(Function(s) s.Id = ServicesId) _
                             And p.Keywords.Any(Function(k) k.Status = KeywordStatus) _
                             Select p
    
    Zack Peterson : The function "Any" was the clue I needed. Thank you.

0 comments:

Post a Comment