【问题标题】:DocumentDb .NET Core SDK - IQueryable.OrderBy generates invalid queryDocumentDb .NET Core SDK - IQueryable.OrderBy 生成无效查询
【发布时间】:2017-08-27 02:20:46
【问题描述】:

以下代码适用于 ASP.NET Core API,该 API 使用 Microsoft.Azure.DocumentDB.Core(版本 1.2.1)包和 LINQ 构造针对 DocumentDb 数据库的查询。

但是,生成的查询无效!

public async Task<IEnumerable<T>> QueryAsync
  (Expression<Func<T, bool>> predicate, string orderByProperty)
{
   client.CreateDocumentQuery<T>(myCollectionUri)
       .Where(predicate)
       .OrderBy(x => orderByProperty)
       .AsDocumentQuery();

   /* rest of the code... */
}

// And I call it:
await repository.QueryAsync<Book>(x => x.Author == "Joe", "Price");

// class Book is a POCO with 3 properties: string Title, string Author, and decimal Price

/*
INVALID generated query:
    SELECT * FROM root WHERE (root["Author"] = "Joe") ORDER BY "Price"

Correct query:
    SELECT * FROM root WHERE (root["Author"] = "Joe") ORDER BY root["Price"]
*/

是否可以改变这种行为?

也许通过在IQueryable&lt;T&gt; 上编写扩展方法并像这样调用它:

client.CreateDocumentQuery<T>(myCollectionUri)
    .Where(predicate)
    .DocumentDbOrderBy(orderByProperty) // new extension method
    .AsDocumentQuery();

【问题讨论】:

  • 为什么您的OrderBy 仍然包含AuthorId,而您希望它与Price 一起使用。另外,您可以建议您使用Price Asc 得到不正确的结果,而不是担心生成的查询
  • @MrinalKamboj 我根据我的真实场景制作了示例。刚刚编辑了问题

标签: c# linq .net-core iqueryable azure-cosmosdb


【解决方案1】:

我使用 Dynamic LINQ 解决了这个问题。

将 using 语句添加到我的存储库类中:

using System.Linq.Dynamic.Core;

以及方法上的一个小改动:

public async Task<IEnumerable<T>> QueryAsync
  (Expression<Func<T, bool>> predicate, string orderByProperty)
{
   client.CreateDocumentQuery<T>(myCollectionUri)
       .Where(predicate)
       .OrderBy(orderByProperty)   // uses dynamic LINQ
       .AsDocumentQuery();

   /* rest of the code... */
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-27
    • 1970-01-01
    • 2018-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多