【问题标题】:Querying cosmos db with SDK使用 SDK 查询 cosmos db
【发布时间】:2020-05-22 04:39:47
【问题描述】:

在构建查询时,我可以使用 Select 方法并创建一个新模型,我可以在其中选择我需要的任何内容。例如:

var queryOptions = new FeedOptions { MaxItemCount = -1, PartitionKey = new PartitionKey("test") };

            var queryResponse = DocumentClient.CreateDocumentQuery<User>(DocumentCollectionUrl, queryOptions)
                                              .Where(x => x.Id == id)
                                              .Select(x => new UserViewModel
                                              {
                                                  Name = x.Name
                                              })
                                              .AsDocumentQuery();

这将创建一个仅选择名称的查询,并且可以正常工作。

现在,如果我创建一个扩展方法,并在 select 方法中调用它,如下所示:

 var queryResponse = DocumentClient.CreateDocumentQuery<User>(DocumentCollectionUrl, queryOptions)
                                              .Where(x => x.Id == id)
                                              .Select(x => x.ToShortModel())
                                              .AsDocumentQuery();

我收到以下错误: {"不支持方法 'ToShortModel'。Windows/10.0.17763 documentdb-netcore-sdk/2.4.0"}

如果我只想选择几个属性,是否需要创建新模型?还是我应该只使用第一个示例?

扩展方法ToShortModel:

public static UserViewModel ToShortModel(this User entity)
        {
            return new UserViewModel
            {
               Name = entity.Name
            };

        }

提前谢谢你。

【问题讨论】:

    标签: c# sdk azure-cosmosdb


    【解决方案1】:

    我相信这是由于投影而发生的。 当 SDK 在第一个 SELECT 中看到表达式时,它能够创建如下所示的查询:

    SELECT c.name
    FROM collections c
    WHERE c.id = id
    

    但是当您在 select 中使用扩展方法时,SDK 不再能够执行查询,因为 ToShortModel 不存在。请记住,SDK 会尝试将 linq 表达式转换为在 CosmosDb 中实际执行的查询。

    一种解决方案可能是创建一个包含所有选择的扩展。 像这样的:

    public static IQueryable<UserViewModel> SelectName<TEntity>(this IQueryable<TEntity> queryable)
    {
         return queryable.Select(x => new UserViewModel
         {
              Name = x.Name
         });
    }
    

    你会这样使用它:

     var queryResponse = DocumentClient.CreateDocumentQuery<User>(DocumentCollectionUrl, queryOptions)
                                                  .Where(x => x.Id == id)
                                                  .SelectName()
                                                  .AsDocumentQuery();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-24
      • 2018-12-17
      • 1970-01-01
      • 2020-07-26
      • 2021-02-16
      • 1970-01-01
      相关资源
      最近更新 更多