SKL*_*LAK 43 c# azure nosql azure-table-storage azure-tablequery
我想获取我的azure表中所有实体的列表.
知道如何写这个查询吗?
我正在使用c#btw.谢谢.
Gau*_*tri 82
要回答您的问题,您可以执行以下操作:
var acc = new CloudStorageAccount(
new StorageCredentials("account name", "account key"), true);
var tableClient = acc.CreateCloudTableClient();
var table = tableClient.GetTableReference("table name");
var entities = table.ExecuteQuery(new TableQuery<MyEntity>()).ToList();
Run Code Online (Sandbox Code Playgroud)
但请记住,表服务在一次调用中最多返回1000个实体.如果表中有超过1000个实体可用,则返回一个continuation token
可用于获取下一组实体的实体.该ExecuteQuery
方法实际上在内部处理此延续令牌,因此如果您因任何原因想要取消此操作,则不能这样做.
更好的方法是使用ExecuteQuerySegmented
方法并让您的应用程序处理令牌.以下是执行此操作的示例代码:
var acc = new CloudStorageAccount(
new StorageCredentials("account name", "account key"), true);
var tableClient = acc.CreateCloudTableClient();
var table = tableClient.GetTableReference("table name");
TableContinuationToken token = null;
var entities = new List<MyEntity>();
do
{
var queryResult = table.ExecuteQuerySegmented(new TableQuery<MyEntity>(), token);
entities.AddRange(queryResult.Results);
token = queryResult.ContinuationToken;
} while (token != null);
Run Code Online (Sandbox Code Playgroud)
使用较新的 Azure.Data.Tables SDK,现在时间要短得多,特别是在使用System.Linq.Async nuget 包时。这样你就可以简单地写:
/// <summary>
/// Returns all rows in the table
/// </summary>
/// <typeparam name="T">Implementation of ITableEntity</typeparam>
/// <param name="tableClient">The authenticated TableClient</param>
/// <returns></returns>
public static async Task<List<T>> GetAllEntitiesAsync<T>(this TableClient tableClient) where T : class, ITableEntity, new()
{
return await tableClient.QueryAsync<T>(maxPerPage: 1000).ToListAsync().ConfigureAwait(false);
}
Run Code Online (Sandbox Code Playgroud)
注意:通过一次请求 1000 行(最大),可以大大减少请求总量。
如果您不需要每次都需要所有行,那么使用以下方法按需(懒惰地)检索项目会更有效yield
:
public async Task<IEnumerable<T>> GetAll<T>(string tableName) where T : class
{
var table = this.GetCloudTable(tableName);
TableContinuationToken token = null;
do
{
var q = new TableQuery<T>();
var queryResult = await table.ExecuteQuerySegmentedAsync(q, token);
foreach (var item in queryResult.Results)
{
yield return item;
}
token = queryResult.ContinuationToken;
} while (token != null);
}
Run Code Online (Sandbox Code Playgroud)
使用这种方法,您可以获得所有行,但是如果您循环遍历结果GetAll()
并找到您要查找的内容,您可以只break
执行循环,并且该GetAll()
方法将停止而不从表中检索下一行。
归档时间: |
|
查看次数: |
33742 次 |
最近记录: |