您现在访问的是微软AZURE全球版技术文档网站,若需要访问由世纪互联运营的MICROSOFT AZURE中国区技术文档网站,请访问 https://docs.azure.cn.

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.

在所有开发环境中自动提供对该绑定的支持。Support for this binding is automatically provided in all development environments. 无需手动安装包或注册扩展。You don't have to manually install the package or register the extension.

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

在 Functions 1.x 中,存储触发器和绑定使用 Azure 存储 SDK 版本 7.2.1(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.xPackages - Functions 2.x

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.

下表说明了如何在每个开发环境中添加对此绑定的支持。The following table tells how to add support for this binding in each development environment.

开发环境Development environment 添加支持To add support in
Functions 2.xFunctions 2.x
本地开发 - C# 类库Local development - C# class library 安装包Install the package
本地开发 - C# 脚本、JavaScript、F#、Java 和 PythonLocal development - C# script, JavaScript, F#, Java and Python 注册扩展Register the extension
门户开发Portal development 添加输出绑定时安装Install when adding output binding

若要了解如何更新门户中的现有绑定扩展而不必重新发布函数应用项目,请参阅更新扩展To learn how to update existing binding extensions in the portal without having to republish your function app project, see Update your extensions.

输入Input

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

输入 - 示例Input - example

参阅语言特定的示例:See the language-specific example:

输入 - C# 示例 - 一个实体Input - C# example - one entity

以下示例演示读取单个表行的 C# 函数The following example shows a C# function that reads a single table row.

行键值“{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}");
    }
}

输入 - C# 示例 - IQueryableInput - C# example - IQueryable

以下示例演示读取多个表行的 C# 函数The following example shows a C# function that reads multiple table rows. 请注意,MyPoco 类派生自 TableEntityNote that 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}");
        }
    }
}

输入 - C# 示例 - CloudTableInput - C# example - CloudTable

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 日志表的 2.x 函数示例:Here's an example of a 2.x 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.

输入 - C# 脚本示例 - 一个实体Input - C# script example - one entity

以下示例演示 function.json 文件中的一个表输入绑定以及使用该绑定的 C# 脚本代码。The following example shows a table input binding in a function.json file and C# script code that uses the binding. 该函数使用队列触发器来读取单个表行。The function uses a queue trigger to read a single table row.

function.json 文件指定 partitionKeyrowKeyThe function.json file specifies a partitionKey and a rowKey. rowKey 值“{queueTrigger}”指示行键来自队列消息字符串。The rowKey value "{queueTrigger}" indicates that the row key comes from the queue message string.

{
  "bindings": [
    {
      "queueName": "myqueue-items",
      "connection": "MyStorageConnectionAppSetting",
      "name": "myQueueItem",
      "type": "queueTrigger",
      "direction": "in"
    },
    {
      "name": "personEntity",
      "type": "table",
      "tableName": "Person",
      "partitionKey": "Test",
      "rowKey": "{queueTrigger}",
      "connection": "MyStorageConnectionAppSetting",
      "direction": "in"
    }
  ],
  "disabled": false
}

配置部分解释了这些属性。The configuration section explains these properties.

C# 脚本代码如下所示:Here's the C# script code:

public static void Run(string myQueueItem, Person personEntity, ILogger log)
{
    log.LogInformation($"C# Queue trigger function processed: {myQueueItem}");
    log.LogInformation($"Name in Person entity: {personEntity.Name}");
}

public class Person
{
    public string PartitionKey { get; set; }
    public string RowKey { get; set; }
    public string Name { get; set; }
}

输入 - C# 脚本示例 - IQueryableInput - C# script example - IQueryable

以下示例演示 function.json 文件中的一个表输入绑定以及使用该绑定的 C# 脚本代码。The following example shows a table input binding in a function.json file and C# script code that uses the binding. 该函数读取队列消息中指定的分区键的实体。The function reads entities for a partition key that is specified in a queue message.

function.json 文件如下所示:Here's the function.json file:

{
  "bindings": [
    {
      "queueName": "myqueue-items",
      "connection": "MyStorageConnectionAppSetting",
      "name": "myQueueItem",
      "type": "queueTrigger",
      "direction": "in"
    },
    {
      "name": "tableBinding",
      "type": "table",
      "connection": "MyStorageConnectionAppSetting",
      "tableName": "Person",
      "direction": "in"
    }
  ],
  "disabled": false
}

配置部分解释了这些属性。The configuration section explains these properties.

C# 脚本代码添加对 Azure 存储 SDK 的引用,以便实体类型可以从 TableEntity 派生。The C# script code adds a reference to the Azure Storage SDK so that the entity type can derive from TableEntity:

#r "Microsoft.WindowsAzure.Storage"
using Microsoft.WindowsAzure.Storage.Table;
using Microsoft.Extensions.Logging;

public static void Run(string myQueueItem, IQueryable<Person> tableBinding, ILogger log)
{
    log.LogInformation($"C# Queue trigger function processed: {myQueueItem}");
    foreach (Person person in tableBinding.Where(p => p.PartitionKey == myQueueItem).ToList())
    {
        log.LogInformation($"Name: {person.Name}");
    }
}

public class Person : TableEntity
{
    public string Name { get; set; }
}

输入 - C# 脚本示例 - CloudTableInput - C# script example - CloudTable

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 日志表的 2.x 函数示例:Here's an example of a 2.x function that queries an Azure Functions log table:

{
  "bindings": [
    {
      "name": "myTimer",
      "type": "timerTrigger",
      "direction": "in",
      "schedule": "0 */1 * * * *"
    },
    {
      "name": "cloudTable",
      "type": "table",
      "connection": "AzureWebJobsStorage",
      "tableName": "AzureWebJobsHostLogscommon",
      "direction": "in"
    }
  ],
  "disabled": false
}
#r "Microsoft.WindowsAzure.Storage"
using Microsoft.WindowsAzure.Storage.Table;
using System;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;

public static async Task Run(TimerInfo myTimer, 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, 
            "a")));

    // 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}");
    }
}

public class LogEntity : TableEntity
{
    public string OriginalName { get; set; }
}

有关如何使用 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.

输入 - F# 示例Input - F# example

以下示例演示 function.json 文件中的一个表输入绑定以及使用该绑定的 F# 脚本代码。The following example shows a table input binding in a function.json file and F# script code that uses the binding. 该函数使用队列触发器来读取单个表行。The function uses a queue trigger to read a single table row.

function.json 文件指定 partitionKeyrowKeyThe function.json file specifies a partitionKey and a rowKey. rowKey 值“{queueTrigger}”指示行键来自队列消息字符串。The rowKey value "{queueTrigger}" indicates that the row key comes from the queue message string.

{
  "bindings": [
    {
      "queueName": "myqueue-items",
      "connection": "MyStorageConnectionAppSetting",
      "name": "myQueueItem",
      "type": "queueTrigger",
      "direction": "in"
    },
    {
      "name": "personEntity",
      "type": "table",
      "tableName": "Person",
      "partitionKey": "Test",
      "rowKey": "{queueTrigger}",
      "connection": "MyStorageConnectionAppSetting",
      "direction": "in"
    }
  ],
  "disabled": false
}

配置部分解释了这些属性。The configuration section explains these properties.

F# 代码如下所示:Here's the F# code:

[<CLIMutable>]
type Person = {
  PartitionKey: string
  RowKey: string
  Name: string
}

let Run(myQueueItem: string, personEntity: Person) =
    log.LogInformation(sprintf "F# Queue trigger function processed: %s" myQueueItem)
    log.LogInformation(sprintf "Name in Person entity: %s" personEntity.Name)

输入 - JavaScript 示例Input - JavaScript example

以下示例演示了 function.json 文件中的表输入绑定以及使用该绑定的 JavaScript 代码The following example shows a table input binding in a function.json file and JavaScript code that uses the binding. 该函数使用队列触发器来读取单个表行。The function uses a queue trigger to read a single table row.

function.json 文件指定 partitionKeyrowKeyThe function.json file specifies a partitionKey and a rowKey. rowKey 值“{queueTrigger}”指示行键来自队列消息字符串。The rowKey value "{queueTrigger}" indicates that the row key comes from the queue message string.

{
  "bindings": [
    {
      "queueName": "myqueue-items",
      "connection": "MyStorageConnectionAppSetting",
      "name": "myQueueItem",
      "type": "queueTrigger",
      "direction": "in"
    },
    {
      "name": "personEntity",
      "type": "table",
      "tableName": "Person",
      "partitionKey": "Test",
      "rowKey": "{queueTrigger}",
      "connection": "MyStorageConnectionAppSetting",
      "direction": "in"
    }
  ],
  "disabled": false
}

配置部分解释了这些属性。The configuration section explains these properties.

JavaScript 代码如下所示:Here's the JavaScript code:

module.exports = function (context, myQueueItem) {
    context.log('Node.js queue trigger function processed work item', myQueueItem);
    context.log('Person entity name: ' + context.bindings.personEntity.Name);
    context.done();
};

输入 - Java 示例Input - Java example

以下示例显示了 HTTP 触发的函数,该函数返回表存储中指定分区中项的总计数。The following example shows an HTTP triggered function which returns the total count of the items in a specified partition in Table storage.

@FunctionName("getallcount")
public int run(
   @HttpTrigger(name = "req",
                 methods = {HttpMethod.GET},
                 authLevel = AuthorizationLevel.ANONYMOUS) Object dummyShouldNotBeUsed,
   @TableInput(name = "items",
                tableName = "mytablename",  partitionKey = "myparkey",
                connection = "myconnvarname") MyItem[] items
) {
    return items.length;
}

输入 - 特性Input - attributes

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 参数或返回值使用该特性,如以下示例中所示:It 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).

输入 - Java 注释Input - Java annotations

Java 函数运行时库中,对其值将来自表存储的参数使用 @TableInput 注释。In the Java functions runtime library, use the @TableInput annotation on parameters whose value would come from Table storage. 可以将此注释与本机 Java 类型、POJO 或使用了 Optional 的可为 null 的值一起使用。This annotation can be used with native Java types, POJOs, or nullable values using Optional.

输入 - 配置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
类型type 不适用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 筛选器Filter 可选。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”开始,则只能在此处指定该名称的余下部分。If the app setting name begins with "AzureWebJobs", you can specify only the remainder of the name here. 例如,如果将 connection 设置为“MyStorage”,函数运行时将会查找名为“AzureWebJobsMyStorage”的应用设置。For example, if you set connection to "MyStorage", the Functions runtime looks for an app setting that is 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

表存储输入绑定支持以下方案:The Table storage input binding supports the following scenarios:

  • 在 C# 或 C# 脚本中读取一行Read one row in C# or C# script

    设置 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.

  • 在 C# 或 C# 脚本中读取一行或多行Read one or more rows in C# or C# script

    使用方法参数 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.

  • 在 JavaScript 中读取一行或多行Read one or more rows in JavaScript

    设置 filtertake 属性。Set the filter and take properties. 不要设置 partitionKeyrowKeyDon't set partitionKey or rowKey. 使用 context.bindings.<name> 访问输入一个或多个输入表实体。Access the input table entity (or entities) using context.bindings.<name>. 反序列化的对象具有 RowKeyPartitionKey 属性。The deserialized objects have RowKey and PartitionKey properties.

输出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.

输出 - 示例Output - example

参阅语言特定的示例:See the language-specific example:

输出 - C# 示例Output - C# example

以下示例演示使用 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 };
    }
}

输出 - C# 脚本示例Output - C# script example

以下示例演示 function.json 文件中的一个表输出绑定以及使用该绑定的 C# 脚本代码。The following example shows a table output binding in a function.json file and C# script code that uses the binding. 该函数写入多个表实体。The function writes multiple table entities.

function.json 文件如下所示:Here's the function.json file:

{
  "bindings": [
    {
      "name": "input",
      "type": "manualTrigger",
      "direction": "in"
    },
    {
      "tableName": "Person",
      "connection": "MyStorageConnectionAppSetting",
      "name": "tableBinding",
      "type": "table",
      "direction": "out"
    }
  ],
  "disabled": false
}

配置部分解释了这些属性。The configuration section explains these properties.

C# 脚本代码如下所示:Here's the C# script code:

public static void Run(string input, ICollector<Person> tableBinding, ILogger log)
{
    for (int i = 1; i < 10; i++)
        {
            log.LogInformation($"Adding Person entity {i}");
            tableBinding.Add(
                new Person() { 
                    PartitionKey = "Test", 
                    RowKey = i.ToString(), 
                    Name = "Name" + i.ToString() }
                );
        }

}

public class Person
{
    public string PartitionKey { get; set; }
    public string RowKey { get; set; }
    public string Name { get; set; }
}

输出 - F# 示例Output - F# example

以下示例演示 function.json 文件中的一个表输出绑定以及使用该绑定的 F# 脚本代码。The following example shows a table output binding in a function.json file and F# script code that uses the binding. 该函数写入多个表实体。The function writes multiple table entities.

function.json 文件如下所示:Here's the function.json file:

{
  "bindings": [
    {
      "name": "input",
      "type": "manualTrigger",
      "direction": "in"
    },
    {
      "tableName": "Person",
      "connection": "MyStorageConnectionAppSetting",
      "name": "tableBinding",
      "type": "table",
      "direction": "out"
    }
  ],
  "disabled": false
}

配置部分解释了这些属性。The configuration section explains these properties.

F# 代码如下所示:Here's the F# code:

[<CLIMutable>]
type Person = {
  PartitionKey: string
  RowKey: string
  Name: string
}

let Run(input: string, tableBinding: ICollector<Person>, log: ILogger) =
    for i = 1 to 10 do
        log.LogInformation(sprintf "Adding Person entity %d" i)
        tableBinding.Add(
            { PartitionKey = "Test"
              RowKey = i.ToString()
              Name = "Name" + i.ToString() })

输出 - JavaScript 示例Output - JavaScript example

以下示例演示 function.json 文件中的一个表输出绑定以及使用该绑定的 JavaScript 函数The following example shows a table output binding in a function.json file and a JavaScript function that uses the binding. 该函数写入多个表实体。The function writes multiple table entities.

function.json 文件如下所示:Here's the function.json file:

{
  "bindings": [
    {
      "name": "input",
      "type": "manualTrigger",
      "direction": "in"
    },
    {
      "tableName": "Person",
      "connection": "MyStorageConnectionAppSetting",
      "name": "tableBinding",
      "type": "table",
      "direction": "out"
    }
  ],
  "disabled": false
}

配置部分解释了这些属性。The configuration section explains these properties.

JavaScript 代码如下所示:Here's the JavaScript code:

module.exports = function (context) {

    context.bindings.tableBinding = [];

    for (var i = 1; i < 10; i++) {
        context.bindings.tableBinding.push({
            PartitionKey: "Test",
            RowKey: i.toString(),
            Name: "Name " + i
        });
    }
    
    context.done();
};

输出 - 特性Output - attributes

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

该特性的构造函数采用表名称。The attribute's constructor takes the table name. 可对函数的 out 参数或返回值使用该特性,如以下示例中所示:It 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
类型type 不适用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”,函数运行时将会查找名为“AzureWebJobsMyStorage”的应用设置。For example, if you set connection to "MyStorage", the Functions runtime looks for an app setting that is 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.

输出 - 用法Output - usage

表存储输出绑定支持以下方案:The Table storage output binding supports the following scenarios:

  • 以任何语言编写一行Write one row in any language

    在 C# 和 C# 脚本中,可以使用 out T paramName 等方法参数或函数返回值访问输出表实体。In C# and C# script, access the output table entity by using a method parameter such as out T paramName or the function return value. 在 C# 脚本中,paramName 是在 function.jsonname 属性中指定的值。In C# script, paramName is the value specified in the name property of function.json. 如果 function.json 文件或 Table 特性提供了分区键和行键,则 T 可以是任何可序列化类型。T can be any serializable type if the partition key and row key are provided by the function.json file or the Table attribute. 否则,T 必须是包含 PartitionKeyRowKey 属性的类型。Otherwise, T must be a type that includes PartitionKey and RowKey properties. 在此方案中,T 通常实现 ITableEntity 或派生自 TableEntity,但不一定非要这样。In this scenario, T typically implements ITableEntity or derives from TableEntity, but it doesn't have to.

  • 用 C# 或 C# 脚本写入一行或多行Write one or more rows in C# or C# script

    在 C# 和 C# 脚本中,可以使用方法参数 ICollector<T> paramNameIAsyncCollector<T> paramName 访问输出表实体。In C# and C# script, access the output table entity by using a method parameter ICollector<T> paramName or IAsyncCollector<T> paramName. 在 C# 脚本中,paramName 是在 function.jsonname 属性中指定的值。In C# script, paramName is the value specified in the name property of function.json. T 指定要添加的实体的架构。T specifies the schema of the entities you want to add. 通常,T 派生自 TableEntity 或实现 ITableEntity,但不一定非要这样。Typically, T derives from TableEntity or implements ITableEntity, but it doesn't have to. 此方案不使用 function.json 中的分区键和行键值,也不使用 Table 特性构造函数。The partition key and row key values in function.json or the Table attribute constructor are not used in this scenario.

    一种替代方法是使用 CloudTable 方法参数通过 Azure 存储 SDK 来写入表。An alternative is to 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. 有关绑定到 CloudTable 的代码的示例,请参阅本文前面的 C#C# 脚本的输入绑定示例。For an example of code that binds to CloudTable, see the input binding examples for C# or C# script earlier in this article.

  • 在 JavaScript 中写入一行或多行Write one or more rows in JavaScript

    在 JavaScript 函数中,可以使用 context.bindings.<name> 访问表输出。In JavaScript functions, access the table output using context.bindings.<name>.

异常和返回代码Exceptions and return codes

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

后续步骤Next steps