首页 文章

使用Linq的Select查询DocumentDB以获取属性列表

提问于
浏览
1

使用Azure的DocumentDb和.NET API,我有以下方法,非常适合检索整个文档的列表:

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;
    }

现在,我并不总是希望返回整个文档(特别是考虑到DocumentDb RU定价模型),所以我认为我应该能够像这样添加.Select投影:

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;
        }

用法:

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

但第二种方法总是返回0结果 . 显然我正在咆哮错误的树 .

知道为选择多个属性的查询返回动态对象列表的正确方法是什么(例如 "SELECT d.id, d.MyVal FROM Items d WHERE d.DocType=0" )或者只选择了一个属性的简单列表(例如 "SELECT d.id FROM Items d WHERE d.DocType=0" )?

1 回答

  • 1

    如果实体类中的 ID 属性没有 [JsonProperty(PropertyName = "id")] ,我可以重新发出此问题 . 如果未包含,请尝试使用以下代码:

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

    Note :该字段为 case sensitive .

相关问题