Skip to content

Instantly share code, notes, and snippets.

@wingkwong
Created January 9, 2020 14:26
Show Gist options
  • Save wingkwong/2d074f1e9391d682758b8524efafcad4 to your computer and use it in GitHub Desktop.
Save wingkwong/2d074f1e9391d682758b8524efafcad4 to your computer and use it in GitHub Desktop.
Azure Storage CRUD Operations Using C#
using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Collections.Generic;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Table;
namespace azure.storage.crud.operations
{
public class Operations
{
private static string _connectionString = "<YOUR_CONNECTION_STRING>";
public static async Task entryPoint(){
var storageAccount = CloudStorageAccount
.Parse(_connectionString);
var tableClient = storageAccount.CreateCloudTableClient();
var table = tableClient.GetTableReference("YOUR_TABLE");
await table.CreateIfNotExistsAsync();
// YOUR LOGIC GOES HERE
}
public static async Task AddAsync<T>(
CloudTable table, T entity) where T : TableEntity
{
var insertOperation = TableOperation.Insert(entity);
await table.ExecuteAsync(insertOperation);
}
public static async Task AddBatchAsync<T>(
CloudTable table, IEnumerable<T> entities) where T : TableEntity
{
var batchOperation = new TableBatchOperation();
foreach (var entity in entities)
batchOperation.Insert(entity);
await table.ExecuteBatchAsync(batchOperation);
}
public static async Task<T> GetAsync<T>(
CloudTable table, string pk, string rk) where T : TableEntity
{
var retrieve = TableOperation.Retrieve<YOUR_TABLE_OBJECT>(pk, rk);
var result = await table.ExecuteAsync(retrieve);
return (T)result.Result;
}
public static async Task DeleteAsync<T>(
CloudTable table, T entity) where T : TableEntity
{
var retrieve = TableOperation.Delete(entity);
await table.ExecuteAsync(retrieve);
}
public static async Task<List<YOUR_TABLE_OBJECT>> FindByFieldAsync(
CloudTable table, string field)
{
var filterCondition = TableQuery.GenerateFilterCondition("<FIELD>", QueryComparisons.Equal, field);
var query = new TableQuery<YOUR_TABLE_OBJECT>().Where(filterCondition);
var results = await table.ExecuteQuerySegmentedAsync(query, null);
return results.ToList();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment