简体   繁体   中英

Filter parent/child table (one to many association) in linq query based on entities in child table?

I have a table (Projects) which is linked to projectVersions on projectID

projectVersions contains several columns on which I'd like to filter a returned project (and associated projectVersions) list. For example there is a "capacity" column and a "country" column. I am doing a filtered list of projects on one page and I'd like to include all projects where any one of the associated projectVersions has a capacity of 750ml and a country of "France" for example.

It may be that a particular parameter is not set and so I pass a zero to indicate not to filter on that.

I guess this needs some kind of subquery as when I try and do something like this:

  thisList = (From p In dc.tblProjects _  
             Where ((Brand = 0) Or (p.Brand = Brand)) _  
             And ((brandVariant = 0) Or (p.brandVariant = brandVariant)) _  
             And ((sizeCapacity = 0) Or (p.tblProjectVersions.sizeCapacity.xxx = sizeCapacity)) _  
                                 Order By p.dateCreated Ascending _  
                                 Select p).ToList  

it doesn't work as the "xxx" bit, being one-to-many, expects me to specify an item to get at the entities within and yet I want to query where ANY of the associated versions match one of the criteria.

If I understand correctly, the issue is in

 Or (p.tblProjectVersions.sizeCapacity.xxx = sizeCapacity)

Since "tblProjectVersions" is a collection, and you want to find where "any" of the associated versions match the criteria, do:

 Or (p.tblProjectVersions.Any(Function(t) t.sizeCapacity.xxx = sizeCapacity))

This will check to see if there is any element inside of the table with the appropriate "sizeCapacity".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM