0

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?

Peter PitLock
  • 1,823
  • 7
  • 34
  • 71
  • Are you using c# ? `.cs` or `.csx` file ? Please provide more information. what is the version of the azure storage table nuget package that you are using ? Btw you're disclaimer is wrong, the normal doc applies to azure function. Have you read about table binding ? – Thomas Jan 24 '18 at 20:43

1 Answers1

3

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);
}
Mikhail Shilkov
  • 34,128
  • 3
  • 68
  • 107