Как подключить Azure Functions 2.0 CosmosDB с помощью привязок ввода и вывода? - PullRequest
0 голосов
/ 29 января 2019

У меня проблемы с выяснением того, как получить доступ к CosmosDB одновременно с привязкой входа и выхода в функции Azure 2.0.

Я могу из одной функции HttpTrigger получить объект json из моей коллекции cosmosDB ииз другой функции HttpTrigger запишите объект json в коллекцию

Я не могу понять, как сначала прочитать объект json из коллекции cosmosDB, внести в него некоторые изменения и снова записать его изв той же функции.

Код ниже должен обрисовать в общих чертах мой вопрос

[FunctionName("WebrootConnector")]
        public static void Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            [CosmosDB(
                databaseName: "customersDB",
                collectionName: "customers",
                ConnectionStringSetting = "CosmosDBConnection", 
                CreateIfNotExists = true,
                Id = "999",
                PartitionKey = "/id")] 
                Customers customersObject, // in binding
                out dynamic customersDocumentToDB, // out binding
                ILogger log)
        {
            // Chect if a customersObject is recieved from cosmosDB
            if (customersObject == null)
            {
                // Create a new Customers object
                customersObject = new Customers();
                // Set the id of the database document (should always be the same)
                customersObject.Id = 999;
                // Create a new empty customer list on the customers object
                customersObject.customers = new List<Customer>();

                // Add some customers to the list

            } 
            else
            {
                // if a object is received from the database
                // do something with it.
            }

            if (customersObject.customers != null)
            {
                // Write the object back to the cosmosDB collection
                customersDocumentToDB = customersObject;
                log.LogInformation($"Data written to customerDB");
            }
            else
            {
                customersDocumentToDB = null;
                log.LogInformation($"Nothing to write to database");
            }
         }

Ответы [ 2 ]

0 голосов
/ 01 февраля 2019

Просто для дальнейшего использования, если у других возникнет такая же проблема

Это то, что сработало для меня.

[FunctionName("WebrootConnector")]
        public static void Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
            [CosmosDB(
                databaseName: "customersDB",
                collectionName: "customers",
                ConnectionStringSetting = "CosmosDBConnection",
                Id = "999"
            )]
                Customers customersObject, // in binding
            [CosmosDB(
                databaseName: "customersDB",
                collectionName: "customers",
                CreateIfNotExists = true,
                ConnectionStringSetting = "CosmosDBConnection"
            )]
                out Customers customersDocumentToDB, // out binding
                ILogger log)
        {
            if (customersObject == null)
            {
                // Create a new Customers object
                customersObject = new Customers();
                // Set the id of the database document (should always be the same)
                customersObject.Id = "999";
                // Create a new empty customer list on the customers object
                customersObject.customers = new List<Customer>();

            } 
            else
            {
                // if a object is received from the database
                // do something with it.
            }

            if (customersObject.customers != null)
            {
                // Write the object back to the cosmosDB collection
                customersDocumentToDB = customersObject;
                log.LogInformation($"Data written to customerDB");
            }
            else
            {
                customersDocumentToDB = null;
                log.LogInformation($"Nothing to write to database");
            }
         }

Класс Customer:

public class Customers
    {
        [JsonProperty("id")]
        public string Id { get; set; }
        [JsonProperty("lastUpdated")]
        public System.DateTime lastUpdated { get; set; }
        [JsonProperty("customers")]
        public List<Customer> customers { get; set; }
    }

public class Customer
    {
        [JsonProperty("customerId")]
        public int customerID { get; set; }
        [JsonProperty("customerName")]
        public string customerName { get; set; }
        [JsonProperty("customerKeycode")]
        public string customerKeyCode { get; set; }
    }

После добавления привязок, одного для входных данных и одного для выходных данных, и изменения моего параметра id класса CustomersObject на строку вместо int все работало нормально, за исключением того, что в привязке in всегда возвращался CustomersObject = null, даже если у меня в коллекции был документ сid = "999", созданный привязкой out.

Я обнаружил, что решение для меня - удалить коллекцию в моем cosmosDB на портале Azure и добавить CreateIfNotExists = true в привязку out.Это позволяет привязке out создавать коллекцию без PartitionKey (что невозможно из портала Azure через веб-интерфейс, так как это требуется), а затем удаляет PartitionKey = "/ id" из привязки in.

Теперь все работает как положено: -)

Может быть, я неправильно использовал PartitionKey? ...

0 голосов
/ 29 января 2019

Вы должны использовать две отдельные привязки , одну для входа (ваш запрос), одну для выхода.Полный список находится в официальных документах для привязок .

[FunctionName("WebrootConnector")]
public static void Run(
    [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
    [CosmosDB(
        databaseName: "customersDB",
        collectionName: "customers",
        ConnectionStringSetting = "CosmosDBConnection", 
        CreateIfNotExists = true,
        Id = "999",
        PartitionKey = "/id")] 
        Customers customersObject, // in binding
     [CosmosDB(
        databaseName: "customersDB",
        collectionName: "customers",
        ConnectionStringSetting = "CosmosDBConnection"] 
        out dynamic customersDocumentToDB, // out binding
        ILogger log)

Если вы хотите сохранить более 1 документа, вы можете использовать IAsyncCollector:

[FunctionName("WebrootConnector")]
public static void Run(
    [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
    [CosmosDB(
        databaseName: "customersDB",
        collectionName: "customers",
        ConnectionStringSetting = "CosmosDBConnection", 
        CreateIfNotExists = true,
        Id = "999",
        PartitionKey = "/id")] 
        Customers customersObject, // in binding
     [CosmosDB(
        databaseName: "customersDB",
        collectionName: "customers",
        ConnectionStringSetting = "CosmosDBConnection"] 
        IAsyncCollector<dynamic> customersDocumentToDB, // out binding
        ILogger log)

А когда вы хотите сохранить документ, звоните await customersDocumentToDB.AddAsync(newDocument).

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...