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 Storage 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. 替代方式是使用 Azure 儲存體 SDK,藉此利用 CloudTable 方法參數來讀取資料表。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」的參考,讓實體類型可以衍生自 TableEntityThe 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. 替代方式是使用 Azure 儲存體 SDK,藉此利用 CloudTable 方法參數來讀取資料表。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.
  • StorageAccount 屬性套用至與 Table 屬性相同的參數。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 或可為 null 的值使用<選擇性的 T >。This annotation can be used with native Java types, POJOs, or nullable values using Optional<T>.

輸入 - 組態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 property 描述Description
typetype n/an/a 必須設為 tableMust be set to table. 當您在 Azure 入口網站中建立繫結時,會自動設定此屬性。This property is set automatically when you create the binding in the Azure portal.
directiondirection n/an/a 必須設為 inMust be set to in. 當您在 Azure 入口網站中建立繫結時,會自動設定此屬性。This property is set automatically when you create the binding in the Azure portal.
namename n/an/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 連接Connection 應用程式設定的名稱包含要用於此繫結的儲存體連接字串。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# 指令碼中,paramNamefunction.jsonname 屬性中指定的值。In C# script, paramName is the value specified in the name property of function.json. T 通常是實作 ITableEntity 的型別或衍生自 TableEntityT 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# 指令碼中,paramNamefunction.jsonname 屬性中指定的值。In C# script, paramName is the value specified in the name property of function.json. T 通常是實作 ITableEntity 的型別或衍生自 TableEntityT 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. 替代方式是使用 Azure 儲存體 SDK,藉以使用 CloudTable paramName 方法參數 (英文) 來讀取資料表。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.

OutputOutput

使用 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

下列範例示範 C# 函式,該函式會使用 HTTP 觸發程序來寫入單一資料表資料列。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 property 描述Description
typetype n/an/a 必須設為 tableMust be set to table. 當您在 Azure 入口網站中建立繫結時,會自動設定此屬性。This property is set automatically when you create the binding in the Azure portal.
directiondirection n/an/a 必須設為 outMust be set to out. 當您在 Azure 入口網站中建立繫結時,會自動設定此屬性。This property is set automatically when you create the binding in the Azure portal.
namename n/an/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 連接Connection 應用程式設定的名稱包含要用於此繫結的儲存體連接字串。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# 指令碼中,paramNamefunction.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# 指令碼中,paramNamefunction.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.

    替代方式是藉由使用 Azure 儲存體 SDK,利用 CloudTable 方法參數來寫入資料表。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
Bob、資料表、佇列Blob, Table, Queue 儲存體錯誤碼Storage Error Codes
Bob、資料表、佇列Blob, Table, Queue 疑難排解Troubleshooting

後續步驟Next steps