开发者

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

开发者 https://www.devze.com 2023-02-11 14:29 出处:网络
The following query works fine where I expand over a navigation property, Schedules, which has a many to 1 relationship with the AssociatedListing 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("Associated开发者_如何学编程Listing/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!


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号