Search code examples
c#azure-functionsazure-cosmosdb

Azure Function V4 how to read/write to a CosmosDB


I have two Azure Functions running in dotnet-isolated mode that I am upgrading to V4 (they were V3 dotnet mode). The functions used the old WebJobs namespace using the [CosmosDB] attribute in the function definition.

Unfortunately, this attribute is no longer supported in dotnet-isolated mode as I am now using the Microsoft.Azure.Functions.Worker namespaces; it appears that the existing documentation that I can find on Azure functions has not been updated.

How do I read and write to Cosmos DB using an Azure Function activated by an HTTP Trigger in dotnet-isolated mode?

Basically, I have a read function which takes a documentId, looks it up and returns the record as a MyDoc, and a write function which takes a MyDoc and writes the fields into cosmos db.

Regards.


Solution

  • Based on Microsoft Documentation its available in package :

    Microsoft.Azure.Functions.Worker.Extensions.CosmosDB
    

    here is working example from Microsoft documentation with azure function v 4 isolated mode For Input :

    [Function(nameof(DocByIdFromJSON))]
    public void DocByIdFromJSON(
        [QueueTrigger("todoqueueforlookup")] ToDoItemLookup toDoItemLookup,
        [CosmosDBInput(
            databaseName: "ToDoItems",
            containerName: "Items",
            Connection  = "CosmosDBConnection",
            Id = "{ToDoItemId}",
            PartitionKey = "{ToDoItemPartitionKeyValue}")] ToDoItem toDoItem)
    {
        _logger.LogInformation($"C# Queue trigger function processed Id={toDoItemLookup?.ToDoItemId} Key={toDoItemLookup?.ToDoItemPartitionKeyValue}");
    
        if (toDoItem == null)
        
            _logger.LogInformation($"ToDo item not found");
        }
        else
        {
            _logger.LogInformation($"Found ToDo item, Description={toDoItem.Description}");
        }
    }
    

    here is a link also for the documentation: https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-cosmosdb-v2-input?tabs=python-v2%2Cisolated-process%2Cnodejs-v4%2Cextensionv4&pivots=programming-language-csharp

    and for output binding:

     [FunctionName("WriteOneDoc")]
        public static void Run(
            [QueueTrigger("todoqueueforwrite")] string queueMessage,
            [CosmosDB(
                databaseName: "ToDoItems",
                containerName: "Items",
                Connection = "CosmosDBConnection")]out dynamic document,
            ILogger log)
        {
            document = new { Description = queueMessage, id = Guid.NewGuid() };
    
            log.LogInformation($"C# Queue trigger function inserted one row");
            log.LogInformation($"Description={queueMessage}");
        }
    

    Link also for Output Binding documentation