问题
Using this code block
try
{
StorageCredentials creds = new StorageCredentials(accountName, accountKey);
CloudStorageAccount account = new CloudStorageAccount(creds, useHttps: true);
CloudTableClient client = account.CreateCloudTableClient();
CloudTable table = client.GetTableReference("serviceAlerts");
TableOperation retrieveOperation = TableOperation.Retrieve<ServiceAlertsEntity>("ServiceAlerts", "b9ccd839-dd99-4358-b90f-46781b87f933");
TableResult query = table.Execute(retrieveOperation);
if (query.Result != null)
{
outline = outline + ((ServiceAlertsEntity) query.Result).alertMessage + " * ";
}
else
{
Console.WriteLine("No Alerts");
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
I am able to retrieve the single record with the partition and rowkey mentioned in the retrieve.
Is there a way I can get all the records that are stored in the partition of ServiceAlerts?
I have tried a wildcard (*) for the second parameter
TableOperation retrieveOperation = TableOperation.Retrieve<ServiceAlertsEntity>(
"ServiceAlerts","b9ccd839-dd99-4358-b90f-46781b87f933");
but it does not return anything.
回答1:
You need to specify a TableQuery, this will give you all entities or you can specify a TableQuery.GenerateFilterCondition
to filter the rows.
TableQuery<ServiceAlertsEntity> query = new TableQuery<ServiceAlertsEntity>();
foreach (ServiceAlertsEntity entity in table.ExecuteQuery(query))
{
Console.WriteLine("{0}, {1}\t{2}\t{3}", entity.PartitionKey, entity.RowKey,
entity.Field1, entity.Field2);
}
回答2:
If you need further control over the records being returned, you can use ExecuteQuerySegmentedAsync
to retrieve data a page (around 1,000 records) at a time.
var alerts = new List<ServiceAlertsEntity>();
var query = new TableQuery<ServiceAlertsEntity>();
TableContinuationToken continuationToken = null;
do
{
var page = await table.ExecuteQuerySegmentedAsync(query, continuationToken);
continuationToken = page.ContinuationToken;
alerts.AddRange(page.Results);
}
while (continuationToken != null);
Or if you need to restrict your results, e.g. by Partition Key, you can add a filter condition by adding a Where
clause to the query in the above code.
var pk = "abc";
var filterPk = TableQuery.GenerateFilterCondition(
nameof(ServiceAlertsEntity.PartitionKey),
QueryComparisons.Equal, pk);
var query = new TableQuery<ServiceAlertsEntity>().Where(filterPk);
MS Azure reference
回答3:
You're using wrong class. Use TableQuery to retrieve multiple results. https://msdn.microsoft.com/en-us/library/azure/microsoft.windowsazure.storage.table.tablequery.aspx
回答4:
I have done the same process using generic class. Using function app i have achieved this. please find the following codes. First i have created a function app MyEventhubTrigger.cs
using Microsoft.ApplicationInsights;
using Microsoft.ApplicationInsights.DataContracts;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.ServiceBus;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using AzureMonitorFunctions.WebHook;
namespace MyFunctions
{
public static class MyEventhubTrigger
{
[FunctionName("MyEventhubTrigger")]
public static async void Run([EventHubTrigger("%EventHubName%", Connection = "EventHubConnectionString", ConsumerGroup = "devicestatuscg")] string myEventHubMessage, DateTime enqueuedTimeUtc, Int64 sequenceNumber, string offset, ILogger log)
{
log.LogInformation($"C# Event Hub trigger function processed a message: {myEventHubMessage}");
try
{
StorageTableOperation<StorageTable> tableObj = new StorageTableOperation<StorageTable>("EventhubMessages");
Eventhubstorage Eventhubdada = tableObj.GetTableData("Eventhub", "DeviceStatus");
if (Eventhubdada.EnqueuedTime < enqueuedTimeUtc)
{
Eventhubdada.EnqueuedTime = enqueuedTimeUtc;
Eventhubdada.Offset = offset;
Eventhubdada.Sequence = sequenceNumber;
await tableObj.UpdateTableData("Eventhub", "DeviceStatus", Eventhubdada);
}
}
}
catch (Exception ex)
{
log.LogInformation(ex.ToString());
}
}
}
}
Now i have create table storage in azure storage account. And add the same field in a property file. which is StorageTable.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.WindowsAzure.Storage.Table;
namespace MyFunctions
{
public class StorageTable : TableEntity
{
public StorageTable()
{
}
public StorageTable(string PKey, string RKey)
{
PartitionKey = PKey;
RowKey = RKey;
}
public DateTime EnqueuedTime { get; set; }
public Int64 Sequence { get; set; }
public string Offset { get; set; }
}
}
Now I have created a class which can take any TableEntity property class and do the following operation Get/insert/Update. Find the following code for StorageTableOperation.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Table;
using System.Threading.Tasks;
namespace MyFunctions
{
public class StorageTableOperation<T> where T : ITableEntity
{
internal CloudTable cloudTable;
public StorageTableOperation(string tableName)
{
string connectionString = Environment.GetEnvironmentVariable("AzureWebJobsStorage");
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString);
CloudTableClient client = storageAccount.CreateCloudTableClient();
cloudTable = client.GetTableReference(tableName);
}
public T GetTableData(string PartitionKey,string RowKey)
{
TableOperation retOp = TableOperation.Retrieve<T>(PartitionKey, RowKey);
TableResult result = cloudTable.Execute(retOp);
T tableData = (T)result.Result;
return tableData;
}
public async Task<bool> UpdateTableData(string PartitionKey, string RowKey, T tableData)
{
try
{
TableOperation operation = TableOperation.InsertOrMerge(tableData);
TableResult tableResult = await cloudTable.ExecuteAsync(operation);
return true;
}
catch(Exception ex)
{
return false;
}
}
}
}
来源:https://stackoverflow.com/questions/38748426/get-all-records-from-azure-table-storage