Azure Functions 的 Azure 表存储输入绑定Azure Table storage input bindings for Azure Functions

使用 Azure 表存储输入绑定读取 Azure 存储帐户中的表。Use the Azure Table storage input binding to read a table in an Azure Storage account.

示例Example

一个实体One entity

以下示例演示读取单个表行的 C# 函数The following example shows a C# function that reads a single table row. 对于发送到队列的每个消息,将触发该函数。For every message send to the queue, the function will be triggered.

行键值“{queueTrigger}”指示行键来自队列消息字符串。The row key value "{queueTrigger}" indicates that the row key comes from the queue message string.

public class TableStorage
{
    public class MyPoco
    {
        public string PartitionKey { get; set; }
        public string RowKey { get; set; }
        public string Text { get; set; }
    }

    [FunctionName("TableInput")]
    public static void TableInput(
        [QueueTrigger("table-items")] string input, 
        [Table("MyTable", "MyPartition", "{queueTrigger}")] MyPoco poco, 
        ILogger log)
    {
        log.LogInformation($"PK={poco.PartitionKey}, RK={poco.RowKey}, Text={poco.Text}");
    }
}

CloudTableCloudTable

CloudTable 仅在 Functions v2 及更高版本的运行时中受支持。CloudTable is only supported in the Functions v2 and and higher runtimes.

使用 CloudTable 方法参数通过 Azure 存储 SDK 来读取表。Use a CloudTable method parameter to read the table by using the Azure Storage SDK. 下面是一个查询 Azure Functions 日志表的函数示例:Here's an example of a function that queries an Azure Functions log table:

using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.Extensions.Logging;
using Microsoft.Azure.Cosmos.Table;
using System;
using System.Threading.Tasks;

namespace FunctionAppCloudTable2
{
    public class LogEntity : TableEntity
    {
        public string OriginalName { get; set; }
    }
    public static class CloudTableDemo
    {
        [FunctionName("CloudTableDemo")]
        public static async Task Run(
            [TimerTrigger("0 */1 * * * *")] TimerInfo myTimer, 
            [Table("AzureWebJobsHostLogscommon")] CloudTable cloudTable,
            ILogger log)
        {
            log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");

            TableQuery<LogEntity> rangeQuery = new TableQuery<LogEntity>().Where(
                TableQuery.CombineFilters(
                    TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, 
                        "FD2"),
                    TableOperators.And,
                    TableQuery.GenerateFilterCondition("RowKey", QueryComparisons.GreaterThan, 
                        "t")));

            // Execute the query and loop through the results
            foreach (LogEntity entity in 
                await cloudTable.ExecuteQuerySegmentedAsync(rangeQuery, null))
            {
                log.LogInformation(
                    $"{entity.PartitionKey}\t{entity.RowKey}\t{entity.Timestamp}\t{entity.OriginalName}");
            }
        }
    }
}

有关如何使用 CloudTable 的详细信息,请参阅 Azure 表存储入门For more information about how to use CloudTable, see Get started with Azure Table storage.

如果在尝试绑定到 CloudTable 时出现错误消息,请确保引用正确的存储 SDK 版本If you try to bind to CloudTable and get an error message, make sure that you have a reference to the correct Storage SDK version.

IQueryableIQueryable

IQueryable 仅在 Functions v1 运行时中受支持。IQueryable is only supported in the Functions v1 runtime.

以下示例显示了一个 C# 函数,它从 TableEntity 中读取其中派生了 MyPoco 类的多个表行。The following example shows a C# function that reads multiple table rows where the MyPoco class derives from TableEntity.

public class TableStorage
{
    public class MyPoco : TableEntity
    {
        public string Text { get; set; }
    }

    [FunctionName("TableInput")]
    public static void TableInput(
        [QueueTrigger("table-items")] string input, 
        [Table("MyTable", "MyPartition")] IQueryable<MyPoco> pocos, 
        ILogger log)
    {
        foreach (MyPoco poco in pocos)
        {
            log.LogInformation($"PK={poco.PartitionKey}, RK={poco.RowKey}, Text={poco.Text}");
        }
    }
}

特性和注释Attributes and annotations

C# 类库中,请使用以下属性来配置表输入绑定:In C# class libraries, use the following attributes to configure a table input binding:

  • TableAttributeTableAttribute

    该特性的构造函数采用表名称、分区键和行键。The attribute's constructor takes the table name, partition key, and row key. 可对函数的 out 参数或返回值使用该特性,如以下示例中所示:The attribute can be used on an out parameter or on the return value of the function, as shown in the following example:

    [FunctionName("TableInput")]
    public static void Run(
        [QueueTrigger("table-items")] string input, 
        [Table("MyTable", "Http", "{queueTrigger}")] MyPoco poco, 
        ILogger log)
    {
        ...
    }
    

    可以设置 Connection 属性来指定要使用的存储帐户,如以下示例中所示:You can set the Connection property to specify the storage account to use, as shown in the following example:

    [FunctionName("TableInput")]
    public static void Run(
        [QueueTrigger("table-items")] string input, 
        [Table("MyTable", "Http", "{queueTrigger}", Connection = "StorageConnectionAppSetting")] MyPoco poco, 
        ILogger log)
    {
        ...
    }
    

    有关完整示例,请参阅 C# 示例。For a complete example, see the C# example.

  • StorageAccountAttributeStorageAccountAttribute

    提供另一种方式来指定要使用的存储帐户。Provides another way to specify the storage account to use. 构造函数采用包含存储连接字符串的应用设置的名称。The constructor takes the name of an app setting that contains a storage connection string. 可以在参数、方法或类级别应用该特性。The attribute can be applied at the parameter, method, or class level. 以下示例演示类级别和方法级别:The following example shows class level and method level:

    [StorageAccount("ClassLevelStorageAppSetting")]
    public static class AzureFunctions
    {
        [FunctionName("TableInput")]
        [StorageAccount("FunctionLevelStorageAppSetting")]
        public static void Run( //...
    {
        ...
    }
    

要使用的存储帐户按以下顺序确定:The storage account to use is determined in the following order:

  • Table 特性的 Connection 属性。The Table attribute's Connection property.
  • 作为 Table 特性应用到同一参数的 StorageAccount 特性。The StorageAccount attribute applied to the same parameter as the Table attribute.
  • 应用到函数的 StorageAccount 特性。The StorageAccount attribute applied to the function.
  • 应用到类的 StorageAccount 特性。The StorageAccount attribute applied to the class.
  • 函数应用的默认存储帐户(“AzureWebJobsStorage”应用设置)。The default storage account for the function app ("AzureWebJobsStorage" app setting).

配置Configuration

下表解释了在 function.json 文件和 Table 特性中设置的绑定配置属性。The following table explains the binding configuration properties that you set in the function.json file and the Table attribute.

function.json 属性function.json property Attribute 属性Attribute property 说明Description
typetype 不适用n/a 必须设置为 tableMust be set to table. 在 Azure 门户中创建绑定时,会自动设置此属性。This property is set automatically when you create the binding in the Azure portal.
directiondirection 不适用n/a 必须设置为 inMust be set to in. 在 Azure 门户中创建绑定时,会自动设置此属性。This property is set automatically when you create the binding in the Azure portal.
namename 不适用n/a 表示函数代码中的表或实体的变量的名称。The name of the variable that represents the table or entity in function code.
tableNametableName TableNameTableName 表的名称。The name of the table.
partitionKeypartitionKey PartitionKeyPartitionKey 可选。Optional. 要读取的表实体的分区键。The partition key of the table entity to read. 有关如何使用此属性的指导,请参阅用法部分。See the usage section for guidance on how to use this property.
rowKeyrowKey RowKeyRowKey 可选。Optional. 要读取的表实体的行键。The row key of the table entity to read. 有关如何使用此属性的指导,请参阅用法部分。See the usage section for guidance on how to use this property.
taketake TakeTake 可选。Optional. 要在 JavaScript 中读取的最大实体数。The maximum number of entities to read in JavaScript. 有关如何使用此属性的指导,请参阅用法部分。See the usage section for guidance on how to use this property.
filterfilter FilterFilter 可选。Optional. JavaScript 中的表输入的 OData 筛选表达式。An OData filter expression for table input in JavaScript. 有关如何使用此属性的指导,请参阅用法部分。See the usage section for guidance on how to use this property.
连接 connection ConnectionConnection 包含要用于此绑定的存储连接字符串的应用设置的名称。The name of an app setting that contains the Storage connection string to use for this binding. 设置可以是带有“AzureWebJobs”前缀的应用设置的名称,也可以是连接字符串的名称。The setting can be the name of an "AzureWebJobs" prefixed app setting or connection string name. 例如,如果设置名称是“AzureWebJobsMyStorage”,则可以在此处指定“MyStorage”。For example, if your setting name is "AzureWebJobsMyStorage", you can specify "MyStorage" here. Functions 运行时将自动查找名为“AzureWebJobsMyStorage”的应用设置。The Functions runtime will automatically look for an app setting that named "AzureWebJobsMyStorage". 如果将 connection 留空,函数运行时将使用名为 AzureWebJobsStorage 的应用设置中的默认存储连接字符串。If you leave connection empty, the Functions runtime uses the default Storage connection string in the app setting that is named AzureWebJobsStorage.

在本地进行开发时,应用设置将取 local.settings.json 文件的值。When you're developing locally, app settings go into the local.settings.json file.

使用情况Usage

  • 读取一行Read one row in

    设置 partitionKeyrowKeySet partitionKey and rowKey. 使用方法参数 T <paramName> 访问表数据。Access the table data by using a method parameter T <paramName>. 在 C# 脚本中,paramName 是在 function.jsonname 属性中指定的值。In C# script, paramName is the value specified in the name property of function.json . T 通常是实现 ITableEntity 或派生自 TableEntity 的类型。T is typically a type that implements ITableEntity or derives from TableEntity. 此方案中不使用 filtertake 属性。The filter and take properties are not used in this scenario.

  • 读取一行或多行Read one or more rows

    使用方法参数 IQueryable<T> <paramName> 访问表数据。Access the table data by using a method parameter IQueryable<T> <paramName>. 在 C# 脚本中,paramName 是在 function.jsonname 属性中指定的值。In C# script, paramName is the value specified in the name property of function.json . T 必须是实现 ITableEntity 或派生自 TableEntity 的类型。T must be a type that implements ITableEntity or derives from TableEntity. 可以使用 IQueryable 方法执行任何所需的筛选。You can use IQueryable methods to do any filtering required. 此方案中不使用 partitionKeyrowKeyfiltertake 属性。The partitionKey, rowKey, filter, and take properties are not used in this scenario.

    备注

    Functions v2 运行时不支持 IQueryableIQueryable isn't supported in the Functions v2 runtime. 一种替代方法是使用 CloudTable paramName 方法参数通过 Azure 存储 SDK 来读取表。An alternative is to use a CloudTable paramName method parameter to read the table by using the Azure Storage SDK. 如果在尝试绑定到 CloudTable 时出现错误消息,请确保引用正确的存储 SDK 版本If you try to bind to CloudTable and get an error message, make sure that you have a reference to the correct Storage SDK version.

后续步骤Next steps