-
-
Save ThomasPe/378504fc28b617066dd96e52587119ff to your computer and use it in GitHub Desktop.
Azure Table Storage Delete All Rows
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <summary> | |
/// Deletes all rows from the table | |
/// </summary> | |
/// <param name="tableClient">The authenticated TableClient</param> | |
/// <returns></returns> | |
public static async Task DeleteAllEntitiesAsync(this TableClient tableClient) | |
{ | |
// Only the PartitionKey & RowKey fields are required for deletion | |
AsyncPageable<TableEntity> entities = tableClient | |
.QueryAsync<TableEntity>(select: new List<string>() { "PartitionKey", "RowKey" }, maxPerPage: 1000); | |
await entities.AsPages().ForEachAwaitAsync(async page => { | |
// Since we don't know how many rows the table has and the results are ordered by PartitonKey+RowKey | |
// we'll delete each page immediately and not cache the whole table in memory | |
await BatchManipulateEntities(tableClient, page.Values, TableTransactionActionType.Delete).ConfigureAwait(false); | |
}); | |
} | |
/// <summary> | |
/// Groups entities by PartitionKey into batches of max 100 for valid transactions | |
/// </summary> | |
/// <returns>List of Azure Responses for Transactions</returns> | |
public static async Task<List<Response<IReadOnlyList<Response>>>> BatchManipulateEntities<T>(TableClient tableClient, IEnumerable<T> entities, TableTransactionActionType tableTransactionActionType) where T : class, ITableEntity, new() | |
{ | |
var groups = entities.GroupBy(x => x.PartitionKey); | |
var responses = new List<Response<IReadOnlyList<Response>>>(); | |
foreach (var group in groups) | |
{ | |
List<TableTransactionAction> actions; | |
var items = group.AsEnumerable(); | |
while (items.Any()) | |
{ | |
var batch = items.Take(100); | |
items = items.Skip(100); | |
actions = new List<TableTransactionAction>(); | |
actions.AddRange(batch.Select(e => new TableTransactionAction(tableTransactionActionType, e))); | |
var response = await tableClient.SubmitTransactionAsync(actions).ConfigureAwait(false); | |
responses.Add(response); | |
} | |
} | |
return responses; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment