Sergi Papaseit
Sergi Papaseit

Reputation: 16174

Querying a RavenDB index against an external List<T>

I have the following RavenDB Index:

public class RidesByPostcode : AbstractIndexCreationTask<Ride, RidesByPostcode.IndexEntry>
{
    public class IndexEntry
    {
        public string PostcodeFrom { get; set; }
        public string PostcodeTo { get; set; }
    }

    public RidesByPostcode()
    {
        Map = rides => from doc in rides
                       select new
                       {
                           doc.DistanceResult.PostcodeFrom,
                           doc.DistanceResult.PostcodeTo
                       };

        StoreAllFields(FieldStorage.Yes);
    }
}

I also have a list of strings representing postcodes, and I want to get all the Rides for which the PostcodeFrom is in the list of postcodes:

var postcodes = new List<string> { "postcode 1", "postcode 2" };

var rides = _database.Query<RidesByPostcode.IndexEntry, RidesByPostcode>()
            .Where(x => postcodes.Contains(x.PostcodeFrom))
            .OfType<Ride>()
            .ToList();

But of course RavenDb says it cannot understand the .Contains expression.

How can I achieve such a query in RavenDb without having to call .ToList() before the where clause?

Upvotes: 1

Views: 40

Answers (1)

Sergi Papaseit
Sergi Papaseit

Reputation: 16174

Ok, I found the answer: RavenDb's .In() extension method (see the "Where + In" section of the docs).

Apparently I was thinking from the outside in, instead of from the inside out :)

This is the final query:

var rides = _database.Query<RidesByPostcode.IndexEntry, RidesByPostcode>()
            .Where(x => !x.IsAccepted && x.PostcodeFrom.In(postcodes))
            .OfType<Ride>()
            .ToList();

Upvotes: 2

Related Questions