Search code examples
c#azureazure-table-storagepopulate

Populate Azure Table Storage Tables in C#


I am trying to find a good way how to populate Tables of Azure Table Storage just once with C#. Right now, I am creating the tables I need at startup using the CloudTable.CreateIfNotExistAsync(). I mean I could check if the initial entries I need, are already inside and if not create them but maybe there is a more clever way to do it. Maybe the C# SDK has some mechanisms I didn't recognize yet.


Solution

  • I mean I could check if the initial entries I need, are already inside and if not create them but maybe there is a more clever way to do it. Maybe the C# SDK has some mechanisms I didn't recognize yet.

    For your scenario, I would recommend InsertOrReplace operation on entities which will either create an entity if it doesn't exist or replace it if it exists.

    var account = CloudStorageAccount.Parse("UseDevelopmentStorage=true");// new CloudStorageAccount(new StorageCredentials(accountName, accountKey), true);
    
    var tableClient = account.CreateCloudTableClient();
    
    var table = tableClient.GetTableReference("Customer");
    table.CreateIfNotExists();
    
    var entity = new DynamicTableEntity("partitionkey", "rowkey");
    entity.Properties.Add("key", new EntityProperty("value"));
    
    var operation = TableOperation.InsertOrReplace(entity);
    
    var result = await table.ExecuteAsync(operation);
    

    Other option could be to try to create an entity and catch StorageException that will be thrown if the entity already exists.