skeej
skeej

Reputation: 870

Filtering a Linq / Odata query over a 1 to many navigation property

The following query works fine where I expand over a navigation property, Schedules, which has a many to 1 relationship with the AssociatedListing property:

from la in ListingAssociations.Expand("AssociatedListing").Expand("AssociatedListing/Schedules")
where la.ListingId==60
select la

In the results, I can see multiple Schedule objects corresponding to each AssociatedListing object. This is good.

However, when I try to add a filter on any of the Schedules fields:

from la in ListingAssociations.Expand("AssociatedListing").Expand("AssociatedListing/Schedules")
where la.ListingId==60 && la.AssociatedListing.Schedules.StartDate > DateTime.Today
select la

I get the error:

"'System.Collections.ObjectModel.Collection' does not contain a definition for 'StartDate' and no extension method 'StartDate' accepting a first argument of type 'System.Collections.ObjectModel.Collection' could be found...".

So I guess the problem is that StartDate is a field of the Schedule class, and the "Schedules" navigation property is a collection of Schedule objects, hence Schedules.StartDate doesn't make any sense. But there must be some way to specify a filter in this many to 1 situation. How?

Any help would be greatly appreciated!

Upvotes: 0

Views: 1679

Answers (1)

RPM1984
RPM1984

Reputation: 73123

Change your where clause from this:

where la.ListingId==60 
   && la.AssociatedListing.Schedules.StartDate > DateTime.Today

To this:

where la.ListingId==60 
   && la.AssociatedListing.Schedules.All(x => x.StartDate > DateTime.Today)

If you want it so that any of the Schedules have a start date greater than today (instead of filtering to ones where all of them do), change All to Any.

Upvotes: 2

Related Questions