4

I have a object IQueryable which I am trying to dynamically add Where clauses, this works great for columns on Listing object, however now conditionally I would like to add a IN clause to a navigation property (ListingAmenities) which has columns ListingID, AmenityID

I have critiera.AmenityIDs which may contain Amenities I like to filter the results on.

I am trying to achieve the following if there is any amenityIDs in my array

select * from Listings l inner join ListingAmenities a on l.ListingID = a.ListingID where a.AmenityID IN(1,2,3)

here is my code (I am using EF5)

if (criteria.AmenityIDs.Count > 0)
        {
            listings = listings.Where(x => x.ListingAmenities.Any(y => y.AmenityID == criteria.AmenityIDs));
        }

which of course does not work. Important note is that I am adding these WHERE clauses dynamically so that is why I am building up a IQueryable object

Zoinky
  • 4,083
  • 11
  • 40
  • 78

1 Answers1

1

Enumerable.Contains translates into IN in SQL, so you can use:

if (criteria.AmenityIDs.Count > 0)
{
    listings = listings.Where(x => x.ListingAmenities
        .Any(y => criteria.AmenityIDs.Contains(y.AmenityID)));
}

Be careful if the AmenityIDs collection is very long because Contains has performance problems for large collections. But 100 elements or so shouldn't be a problem.

Community
  • 1
  • 1
Slauma
  • 175,098
  • 59
  • 401
  • 420