Search code examples
c#azureazure-functionsazure-cosmosdb

Azure Function CosmosDBInput Binding doesn't return value


I have the following Azure function:

private const string PartitionKey = "/westus2";

public class League
{
    public string id { get; set; }

    public string Description { get; set; }

    public List<string> GameIds { get; set; }
}

[Function("AddGame")]
public async Task<AddGameMultiResponse> AddGame(
    [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = "addgame/{leagueId}")] HttpRequestData req,
    [CosmosDBInput(databaseName: "MyDB",
        collectionName: "Leagues",
        PartitionKey = PartitionKey,
        ConnectionStringSetting = "CosmosDbConnectionString")] IEnumerable<League> leagues,
    [CosmosDBInput(databaseName: "MyDB",
        collectionName: "Leagues",
        Id = "{leagueId}",
        PartitionKey = PartitionKey,
        ConnectionStringSetting = "CosmosDbConnectionString")] League league)
{
}

And when I call it through Postman with the following URI:

http://localhost:7071/api/addgame/5fa8c927-15ad-4fd2-8b9d-4d7b11723021

I see that leagues has one item that has property:

id [string]: "5fa8c927-15ad-4fd2-8b9d-4d7b11723021"

Yet league is null. Looking in the data explorer, I see:

enter image description here

What am I doing wrong here?

Edit: Seems like this works:

   [CosmosDBInput(databaseName: "MyDB",
        collectionName: "Leagues",
        PartitionKey = PartitionKey,
        ConnectionStringSetting = "CosmosDbConnectionString",
        SqlQuery = "SELECT * from c WHERE c.id = {leagueId}")] IEnumerable<League> matchingLeagues

So now I feel like there must be a bug in the CosmosDBInput binding...


Solution

  • PartitionKey might be the key here. What value are you passing?

    The single item read:

    [CosmosDBInput(databaseName: "MyDB",
            collectionName: "Leagues",
            Id = "{leagueId}",
            PartitionKey = PartitionKey,
            ConnectionStringSetting = "CosmosDbConnectionString")] League league)
    

    Requires both Id and PartitionKey to be able to find the item. You got the Id, but what about the PartitionKey? Is the container partitioned by /id? If yes, then the PartitionKey should also have "{leagueId}".

    The reason for League league to be null is simply that the Id/PartitionKey values you are setting do not match with an existing document.