CosmosDB Dotnet - 获取容器中的所有项目

Sea*_*ean 3 .net c# .net-core azure-cosmosdb

我正在尝试找出将所有物品放入容器中的最简单方法。我见过几种实现此目的的方法,但它们似乎都比应有的更复杂。有任何想法吗?

public async Task<IEnumerable<T>> ListAsync()
{
    return _container.//Something
}
Run Code Online (Sandbox Code Playgroud)

我希望存在像 GetAsync 方法这样简单的方法。

public async Task<T> GetAsync(Guid id)
{
    return await _container.ReadItemAsync<T>(id.ToString(), new PartitionKey(id.ToString()));
}
Run Code Online (Sandbox Code Playgroud)

谢谢!:)

AAA*_*ddd 5

您可以GetItemQueryIteratorIAsyncEnumerable

此方法使用带有参数化值的 SQL 语句创建对 Azure Cosmos 数据库中容器下的项目的查询。它返回一个 FeedIterator。有关使用参数化值准备 SQL 语句的更多信息,

例子

//Some Query
public static async IAsyncEnumerable<T> GetAllAsync<T>(string query) 
{ 
   var definition = new QueryDefinition(query);
   var iterator = _container.GetItemQueryIterator<T>(definition);

   while (iterator.HasMoreResults)
      foreach (var item in await iterator.ReadNextAsync().ConfigureAwait(false))
         yield return item;
}
Run Code Online (Sandbox Code Playgroud)

或者您可以提供 null 或空参数列表GetItemQueryIterator

public static async IAsyncEnumerable<T> GetAllAsync<T>() 
{ 
   var iterator = _container.GetItemQueryIterator<T>();

   while (iterator.HasMoreResults)
      foreach (var item in await iterator.ReadNextAsync().ConfigureAwait(false))
         yield return item;
}
Run Code Online (Sandbox Code Playgroud)

用法

await foreach (var item in GetAllAsync<Bob>())
   Console.WriteLine(item);
Run Code Online (Sandbox Code Playgroud)

如果你安装了System.Linq.Async nuget 你可以调用ToListAsync

var results = await GetAllAsync<Bob>().ToListAsync();
Run Code Online (Sandbox Code Playgroud)

如果你不想依赖,你可以自己推出

public static class Extensions
{
   public static ValueTask<List<TSource>> ToListAsync<TSource>(
      this IAsyncEnumerable<TSource> source, 
      CancellationToken cancellationToken = default)
   {
      if (source is null) throw new ArgumentNullException(nameof(source));

      return Local(source, cancellationToken);

      static async ValueTask<List<TSource>> Local(IAsyncEnumerable<TSource> source, CancellationToken cancellationToken)
      {
         var list = new List<TSource>();
         await foreach (var item in source.WithCancellation(cancellationToken).ConfigureAwait(false))
            list.Add(item);
         return list;
      }
   }
}
Run Code Online (Sandbox Code Playgroud)