将Azure函数存储到表存储中

6
我有一个Azure函数,想让它从EventHub获取消息(这非常简单并且有效),然后在运行时使用Table绑定将该信息放入Table Storage中。
以下是目前我的代码实现:
public static async Task Run(string eventHubMessage, TraceWriter log, Binder binder)
{
   var m = JsonConvert.DeserializeObject<Measurement>(eventHubMessage);
   var attributes = new Attribute[]
    {
        new StorageAccountAttribute("AzureWebJobsTest"),
        new TableAttribute(tableName, m.PartitionKey, m.RowKey)
    };

    using(var output = await binder.BindAsync<MyTableEntity>(attributes)) 
    {
        if(output == null)
           log.Info($"4. output is null");
        else
        {
            output.Minimum = m.Minimum;
            output.Maximum = m.Maximum;
            output.Average = m.Average;
            output.Timestamp = m.Timestamp;
            output.ETag = m.ETag;  

            output.WriteEntity(/* Need an operationContext*/)
        }
    }
}
public class MyTableEntity : TableEntity, IDisposable
{
    public double Average { get; set;}
    public double Minimum { get; set;}
    public double Maximum { get; set;}

    bool disposed = false;
    public void Dispose()
    { 
        Dispose(true);
        GC.SuppressFinalize(this);           
    }

   protected virtual void Dispose(bool disposing)
   {
      if (disposed)
         return; 

      if (disposing) 
      {
      }

      disposed = true;
   }
}

我的问题:

1)输出总是为空。

2)即使输出不为空,我也不知道需要什么样的OperationContext,或者调用ITableEntity.Write()是否正确地将其写入表存储中。

预计完成Json绑定:

{
  "bindings": [
    {
      "type": "eventHubTrigger",
      "name": "eventHubMessage",
      "direction": "in",
      "path": "measurements",
      "connection": "MeasurementsConnectionString"
    }
  ],
  "disabled": false
}

@mikhail,我已经添加了JSON。我想根据从中心传入的表名在运行时进行绑定。我有许多表格,需要使用命令式绑定。 - Stuart
2个回答

5
要向表中添加新条目,您应该将绑定到IAsyncCollector而不是实体本身,然后创建一个新实体并调用AddAsync。以下代码片段适用于我:
var attributes = new Attribute[]
{
    new StorageAccountAttribute("..."),
    new TableAttribute("...")
};

var output = await binder.BindAsync<IAsyncCollector<MyTableEntity>>(attributes);     
await output.AddAsync(new MyTableEntity()
{
    PartitionKey = "...",
    RowKey = "...",
    Minimum = ...,
    ...
});

谢谢,这使其正常工作了。现在,每次函数完成时,我都会遇到这个提示。Microsoft.Azure.WebJobs.Host: Error while handling parameter binder after function returned: Microsoft.WindowsAzure.Storage: The specified entity already exists. 这是因为我可能正在尝试插入重复项吗? - Stuart
是的,您正在尝试两次插入相同的分区/行键。在此处查看更新示例:https://dev59.com/-FoV5IYBdhLWcg3wCq8n#36805728 - Mikhail Shilkov

0
如果您想使用DynamicTableEntity,因为在编译时您不知道消息中将包含什么数据,并且您意识到表绑定不再适用于DynamicTableEntities,那么可以使用以下方法:
private static async Task ProcessMessage(string message, DateTime enqueuedTime)
{
    var deviceData = JsonConvert.DeserializeObject<JObject>(message);

    var dynamicTableEntity = new DynamicTableEntity();
    dynamicTableEntity.RowKey = enqueuedTime.ToString("yyyy-MM-dd HH:mm:ss.fff");

    foreach (KeyValuePair<string, JToken> keyValuePair in deviceData)
    {
        if (keyValuePair.Key.Equals("MyPartitionKey"))
        {
            dynamicTableEntity.PartitionKey = keyValuePair.Value.ToString();
        }
        else if (keyValuePair.Key.Equals("Timestamp")) // if you are using a parameter "Timestamp" it has to be stored in a column named differently because the column "Timestamp" will automatically be filled when adding a line to table storage
        {
            dynamicTableEntity.Properties.Add("MyTimestamp", EntityProperty.CreateEntityPropertyFromObject(keyValuePair.Value));
        }
        else
        {
            dynamicTableEntity.Properties.Add(keyValuePair.Key, EntityProperty.CreateEntityPropertyFromObject(keyValuePair.Value));
        }
    }

    CloudStorageAccount storageAccount = CloudStorageAccount.Parse("myStorageConnectionString");
    CloudTableClient tableClient = storageAccount.CreateCloudTableClient();
    CloudTable table = tableClient.GetTableReference("myTableName"); 
    table.CreateIfNotExists();

    var tableOperation = TableOperation.Insert(dynamicTableEntity);
    await table.ExecuteAsync(tableOperation);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接