首页 > 解决方案 > DocumentClient 在 Azure-CosmosDB 中返回单个对象

问题描述

如何更改我的方法以仅返回一个类型的对象Cliente

我的方法:

public IQueryable <Cliente> GetByEmailCpf(string email, string cpf, string colletionId) 
{
  FeedOptions queryOptions = new FeedOptions {
   MaxItemCount = -1
  };

  IQueryable <Cliente> cliente = client.CreateDocumentQuery <Cliente> (
    UriFactory.CreateDocumentCollectionUri(databaseId, colletionId), queryOptions)
   .Where(x => x.Email == email || x.Cpf == cpf);

  return cliente;
}

DocumentQueryException:查询表达式无效,表达式 https://127.0.0.1:8081/dbs/Comosos/colls/Cliente.Where(x => ((x.Email == value(LR.Mobile.Data.Repositories.ModuloProduto. Classes.ClienteRepository+<>c__DisplayClass5_0).email) OrElse (x.Cpf == value(LR.Mobile.Data.Repositories.ModuloProduto.Classes.ClienteRepository+<>c__DisplayClass5_0).cpf))).FirstOrDefault() 不受支持。支持的表达式是“Queryable.Where”、“Queryable.Select”和“Queryable.SelectMany”

标签: c#linqazure-cosmosdb

解决方案


如您的错误所述,您似乎正在尝试使用 FirstOrDefault。这目前不受支持,并且根据 Azure Cosmos 反馈站点,目前不是优先事项:

添加对单个实体检索而不是 IEnumarable 的支持

在那篇文章中,微软推荐了以下解决方法:

相反,我们建议您对 Single() 和 First() 使用 Take(1).AsEnumerable(),然后使用 .First() 或 .Single() 或 .FirstOrDefault()。Take(1) 被翻译为 SELECT TOP 1 并在服务器端进行处理,因此比之前的建议更有效,这就是您想要实现的目标。

通过包含该Take(1)语句,只有第一个结果将被加载到内存中,而不是 where 子句的整个结果。

在您的代码中,这将转化为如下内容:

var query = client.CreateDocumentQuery<Cliente>(
               UriFactory.CreateDocumentCollectionUri(databaseId, colletionId), queryOptions)
             .Where(x => x.Email == email || x.Cpf == cpf)
             .Take(1)
             .AsEnumerable()
             .FirstOrDefault();

正如其他人所提到的,不要忘记更新您的返回类型Cliente


推荐阅读