Search code examples
azure-functionsazure-table-storageazure-tablequery

Azure Function : How to see if a record exists in Table Storage


Note : this is for an Azure Function. The normal C# links on microsoft docs do not apply. It is for an Azure Function.

Scenario:

I need to have 1 entry only per Person, with the last date that this person logged in. This property gets updated every time.

Azure Functions still cannot do an upsert

Therefore I had to split my code into

  1. Creating a new record.

  2. Updating an existing record.

I cannot simply run the update method for both creating and updating :

error CS1061: 'CloudTable' does not contain a definition for 'Add' and no extension method 'Add' accepting a first argument of type 'CloudTable' could be found (are you missing a using directive or an assembly reference?)

So at this point, I need to check if a item already exists, and then I need to call either the create or update function.

How do I use a Azure Function to query Table Storage to see if an item exists?


Solution

  • To check if entity exists, you can just accept it as input parameter and test for null:

    [FunctionName("UpsertEntity")]
    public static HttpResponseMessage Run(
        [HttpTrigger(AuthorizationLevel.Function, "get", Route="test/{id}")] 
        HttpRequestMessage req,
        string id,
        [Table("Test", "default", "{id}")] MyEntity entity)
    {
        return req.CreateResponse(HttpStatusCode.OK, entity != null ? "exists" : "not found");
    }
    

    You could do upsert with a combination of input and output parameters:

    [FunctionName("UpsertEntity")]
    public static HttpResponseMessage Run(
        [HttpTrigger(AuthorizationLevel.Function, "get", Route="test/{id}")] 
        HttpRequestMessage req,
        string id,
        [Table("Test", "default", "{id}")] MyEntity entity,
        [Table("Test", "default", "{id}")] out MyEntity outEntity)
    {
        outEntity = entity ?? new MyEntity { PartitionKey = "default", RowKey = id };
        outEntity.Name = Guid.NewGuid().ToString();
        return req.CreateResponse(HttpStatusCode.OK, id);
    }