Simon Ordo
Simon Ordo

Reputation: 1677

Querying DocumentDB for a list of propertiers using Linq's Select

Using Azure's DocumentDb and the .NET API, I have the following method which works great for retrieving lists of entire documents:

   public async Task<IEnumerable<T>> GetItemsAsync<T>(Expression<Func<T, bool>> predicate)
    {            
        IDocumentQuery<T> query = _Client.CreateDocumentQuery<T>(
            UriFactory.CreateDocumentCollectionUri(_DatabaseId, _Collection),
            new FeedOptions { MaxItemCount = -1 })
            .Where(predicate)
            .AsDocumentQuery();

        List<T> results = new List<T>();
        while (query.HasMoreResults)
        {
            var item = await query.ExecuteNextAsync<T>();
            results.AddRange(item);
        }

        return results;
    }

Now, I don't always want to return the entire document (especially considering the DocumentDb RU pricing model), so I thought I should be able to add a .Select projection like so:

 public async Task<List<TResult>> GetItemsAsync<T, TResult>(Expression<Func<T, bool>> predicate, Expression<Func<T, TResult>> select)
        {
            IDocumentQuery<TResult> query = _Client.CreateDocumentQuery<T>(
                UriFactory.CreateDocumentCollectionUri(_DatabaseId, _Collection),
                new FeedOptions { MaxItemCount = -1 })
                .Where(predicate)
                .Select(select)
                .AsDocumentQuery();

            List<TResult> results = new List<TResult>();
            while (query.HasMoreResults)
            {
                var item = await query.ExecuteNextAsync<TResult>();
                results.AddRange(item);
            }

            return results;
        }

Usage:

var rez = await _docs.GetItemsAsync<ApolloAssetDoc, Guid?>(x => x.MyVal == 5, x => x.ID);

But the second method always return 0 results. Obviously I'm barking up the wrong tree.

Any idea what the correct way to return a list of either dynamic objects for queries where more than one property is selected (eg "SELECT d.id, d.MyVal FROM Items d WHERE d.DocType=0")or a simple list where only a single property is selected (eg "SELECT d.id FROM Items d WHERE d.DocType=0")?

Upvotes: 1

Views: 744

Answers (1)

Tom Sun
Tom Sun

Reputation: 24569

I could repro the issue, if there is no [JsonProperty(PropertyName = "id")] for ID property in the entity Class. If it is not included, please have a try to use the following code:

public class ApolloAssetDoc
    {
        [JsonProperty(PropertyName = "id")]
        public Guid ID { get; set; }
        public string MyVal { get; set; }

    }

Note: The field is case sensitive.

Upvotes: 1

Related Questions