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

本文介绍如何在 Azure Functions 中使用 Azure 表存储绑定。This article explains how to work with Azure Table storage bindings in Azure Functions. Azure Functions 支持 Azure 表存储使用输入和输出绑定。Azure Functions supports input and output bindings for Azure Table storage.

此参考信息面向 Azure Functions 开发人员。This is reference information for Azure Functions developers. Azure Functions 的新手请从以下资源入手:If you're new to Azure Functions, start with the following resources:

包 - Functions 1.xPackages - Functions 1.x

Microsoft.Azure.WebJobs NuGet 包 2.x 版中提供了表存储绑定。The Table storage bindings are provided in the Microsoft.Azure.WebJobs NuGet package, version 2.x. azure-webjobs-sdk GitHub 存储库中提供了此包的源代码。Source code for the package is in the azure-webjobs-sdk GitHub repository.

C# 类库C# class library

对于 C# 类库开发,自动在项目中安装该包。For C# class library development, the package is automatically installed in the project.

Functions 2.x 中的绑定扩展Binding extensions in Functions 2.x

对于 Azure Functions 2.x 版中的本地开发,该包自动注册为绑定扩展For local development in Azure Functions version 2.x, the package is automatically registered as a binding extension.

Functions 1.x 中的 Azure 存储 SDK 版本Azure Storage SDK version in Functions 1.x

在 Functions 1.x 中,存储触发器和绑定使用 7.2.1 版的 Azure 存储 SDK(WindowsAzure.Storage NuGet 包)。In Functions 1.x, the Storage triggers and bindings use version 7.2.1 of the Azure Storage SDK (WindowsAzure.Storage NuGet package). 如果引用另一版本的存储 SDK,而且在函数签名中绑定到某个存储 SDK 类型,则 Functions 运行时可能会报告它不能绑定到该类型。If you reference a different version of the Storage SDK, and you bind to a Storage SDK type in your function signature, the Functions runtime may report that it can't bind to that type. 此解决方案是为了确保项目引用 WindowsAzure.Storage 7.2.1The solution is to make sure your project references WindowsAzure.Storage 7.2.1.

包 - Functions 2.x 及更高版本Packages - Functions 2.x and higher

Microsoft.Azure.WebJobs.Extensions.Storage NuGet 包 3.x 版中提供了表存储绑定。The Table storage bindings are provided in the Microsoft.Azure.WebJobs.Extensions.Storage NuGet package, version 3.x. azure-webjobs-sdk GitHub 存储库中提供了此包的源代码。Source code for the package is in the azure-webjobs-sdk GitHub repository.

使用以下方法在首选开发环境中添加支持。Add support in you preferred development environment using the following methods.

开发环境Development environment 应用程序类型Application type 添加支持To add support
Visual StudioVisual Studio C# 类库C# class library 安装 NuGet 包Install the NuGet package
Visual Studio CodeVisual Studio Code 基于核心工具Based on core tools 注册扩展捆绑包Register the extension bundle

建议安装 Azure Tools 扩展Installing the Azure Tools extension is recommended.
任何其他编辑器/IDEAny other editor/IDE 基于核心工具Based on core tools 注册扩展捆绑包Register the extension bundle
Azure 门户Azure Portal 仅在门户中联机Online only in portal 在添加绑定时安装Installs when adding a binding

请参阅更新扩展以更新现有绑定扩展,而无需重新发布函数应用。See Update your extensions to update existing binding extensions without having to republish your function app.

输入Input

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

一个实体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}");
    }
}

IQueryableIQueryable

以下示例显示了一个 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}");
        }
    }
}

CloudTableCloudTable

Functions v2 运行时不支持 IQueryableIQueryable isn't supported in the Functions v2 runtime. 一种替代方法是使用 CloudTable 方法参数通过 Azure 存储 SDK 来读取表。An alternative is to 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.WindowsAzure.Storage.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.

输入 - 特性和注释Input - 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 Input - 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).

输入 - 配置Input - 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.

输入 - 用法Input - 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.

输出Output

使用 Azure 表存储输出绑定读取将实体写入 Azure 存储帐户中的表。Use an Azure Table storage output binding to write entities to a table in an Azure Storage account.

备注

此输出绑定不支持更新现有实体。This output binding does not support updating existing entities. 请使用 Azure 存储 SDK 中的 TableOperation.Replace 操作来更新现有实体。Use the TableOperation.Replace operation from the Azure Storage SDK to update an existing entity.

以下示例演示使用 HTTP 触发器写入单个表行的 C# 函数The following example shows a C# function that uses an HTTP trigger to write a single table row.

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

    [FunctionName("TableOutput")]
    [return: Table("MyTable")]
    public static MyPoco TableOutput([HttpTrigger] dynamic input, ILogger log)
    {
        log.LogInformation($"C# http trigger function processed: {input.Text}");
        return new MyPoco { PartitionKey = "Http", RowKey = Guid.NewGuid().ToString(), Text = input.Text };
    }
}

输出 - 特性和注释Output - attributes and annotations

C# 类库中,使用 TableAttributeIn C# class libraries, use the TableAttribute.

该特性的构造函数采用表名称。The attribute's constructor takes the table name. 可对函数的 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("TableOutput")]
[return: Table("MyTable")]
public static MyPoco TableOutput(
    [HttpTrigger] dynamic input, 
    ILogger log)
{
    ...
}

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

[FunctionName("TableOutput")]
[return: Table("MyTable", Connection = "StorageConnectionAppSetting")]
public static MyPoco TableOutput(
    [HttpTrigger] dynamic input, 
    ILogger log)
{
    ...
}

有关完整示例,请参阅输出 - C# 示例For a complete example, see Output - C# example.

可以使用 StorageAccount 特性在类、方法或参数级别指定存储帐户。You can use the StorageAccount attribute to specify the storage account at class, method, or parameter level. 有关详细信息,请参阅输入 - 特性For more information, see Input - attributes.

输出 - 配置Output - 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 必须设置为 outMust be set to out. 在 Azure 门户中创建绑定时,会自动设置此属性。This property is set automatically when you create the binding in the Azure portal.
namename 不适用n/a 在函数代码中使用的、表示表或实体的变量名称。The variable name used in function code that represents the table or entity. 设置为 $return 可引用函数返回值。Set to $return to reference the function return value.
tableNametableName TableNameTableName 表的名称。The name of the table.
partitionKeypartitionKey PartitionKeyPartitionKey 要写入的表实体的分区键。The partition key of the table entity to write. 有关如何使用此属性的指导,请参阅用法部分See the usage section for guidance on how to use this property.
rowKeyrowKey RowKeyRowKey 要写入的表实体的行键。The row key of the table entity to write. 有关如何使用此属性的指导,请参阅用法部分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”开始,则只能在此处指定该名称的余下部分。If the app setting name begins with "AzureWebJobs", you can specify only the remainder of the name here. 例如,如果将 connection 设置为“MyStorage”,Functions 运行时将会查找名为“MyStorage”的应用设置。For example, if you set connection to "MyStorage", the Functions runtime looks for an app setting that is named "MyStorage". 如果将 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.

输出 - 用法Output - usage

可以使用方法参数 ICollector<T> paramNameIAsyncCollector<T> paramName 访问输出表实体,其中 T 包括 PartitionKeyRowKey 属性。Access the output table entity by using a method parameter ICollector<T> paramName or IAsyncCollector<T> paramName where T includes the PartitionKey and RowKey properties. 实现 ITableEntity 或继承 TableEntity 时通常会伴随使用这些属性。These properties are often accompanied by implementing ITableEntity or inheriting TableEntity.

另外,还可以使用 CloudTable 方法参数通过 Azure 存储 SDK 来写入到表。Alternatively you can use a CloudTable method parameter to write to 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.

异常和返回代码Exceptions and return codes

绑定Binding 参考Reference
Table 表错误代码Table Error Codes
Blob、表、队列Blob, Table, Queue 存储错误代码Storage Error Codes
Blob、表、队列Blob, Table, Queue 故障排除Troubleshooting

后续步骤Next steps