我目前正在将我的脚趾浸入 azure 桌面存储的水中。
我使用的是Azure.Data.Tables
而不是Microsoft.WindowsAzure.Storage.Table
,因为我可以看出它是较新的版本,它将被维护.
现在我有了这个类,它有方法,一个用于更新插入,一个用于更新插入许多实体:
public class TableRepository
{
private TableServiceClient _tableServiceClient;
private TableClient _tableClient;
public TableRepository(string key, string table)
{
_tableServiceClient = new TableServiceClient(key);
_tableClient = _tableServiceClient.GetTableClient(tableName: table);
}
public async Task AddAsync(TableEntity mapping)
{
await _tableClient.UpsertEntityAsync(mapping);
}
public async Task AddEntitiesToTableAsync(IEnumerable<TableEntity> mappings)
{
foreach (var m in mappings)
{
await _tableClient.UpsertEntityAsync(m);
}
}
}
对于我的批量更新插入,这有效,但对于许多更新插入来说速度很慢,我想看看是否可以批量更新插入实体。
我发现对于 Microsoft.WindowsAzure.Storage.Table
,我可以执行一批操作,并执行如下操作:
public async Task AddEntitiesToTableAsync(IEnumerable<EmailToIdMapping> mappings)
{
// Retrieve the CloudTable instance representing your Azure Storage table
CloudTable table = GetCloudTable(); // Replace with your own logic to get the CloudTable
// Create a List of TableOperation to hold the batch operations
List<TableOperation> batchOperations = new List<TableOperation>();
foreach (var m in mappings)
{
var tableEntity = new DynamicTableEntity(m.PartitionKey, m.RowKey)
{
Properties = new Dictionary<string, EntityProperty>
{
{ "Email", new EntityProperty(m.Email) },
{ "Id", new EntityProperty(m.Id) }
}
};
// Create an InsertOrReplace operation for the entity
TableOperation upsertOperation = TableOperation.InsertOrReplace(tableEntity);
batchOperations.Add(upsertOperation);
}
// Create a TableBatchOperation with the batch operations
TableBatchOperation batchOperation = new TableBatchOperation();
batchOperation.AddRange(batchOperations);
// Execute the batch operation
await table.ExecuteBatchAsync(batchOperation);
}
但是我找不到任何与Azure.Data.Tables
类似的东西,我唯一能想到的就是找到一种更智能的方法来更有效地并行完成我已经在做的事情
我能做什么?
最佳答案
尝试 Azure.Data.Tables
中的 SubmitTransactionAsync
方法
try
{
var actions = new List<TableTransactionAction>();
// Iterate over the entities and add up values
foreach (var entity in entities)
{
var upsertAction = new UpsertEntityAction(entity);
actions.Add(upsertAction);
}
var transaction = new TableTransaction(actions);
var tableClient = client.GetTableClient("<pass-your-table-name-here>");
// Execute as a batch transaction
await tableClient.SubmitTransactionAsync(transaction);
}
catch (Exception e)
{
throw;
}
请注意,为了成功,您应该拥有相同的分区键。否则,据我所知,没有办法可以实现批量交易
关于c# - 如何使用 Azure.Data.Tables 为 azure 表创建批量更新插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76451227/