Entity Functions are a powerful feature of Azure Durable Functions designed to manage the state of discrete entities. They allow you to model stateful, long-running applications by treating an entity as a single, isolated unit of computation and state.
Think of Entity Functions as lightweight actors. Each entity has a unique identifier and maintains its own state. You can perform operations (actions) on an entity, and the state of that entity will be updated accordingly. This is ideal for scenarios like:
Each entity is identified by a unique string, often referred to as the entity ID. This ID is crucial for targeting specific entities to perform operations.
The state of an entity is typically represented as a JSON object. Entity Functions can read, write, and manipulate this state directly.
You invoke operations on an entity by sending messages to its entity ID. These operations can modify the entity's state, perform calculations, or trigger other workflows.
Client functions (or other orchestrator functions) can interact with entity functions using the Durable Functions client APIs. This allows for asynchronous invocation of operations on entities.
Let's consider a basic counter entity that can increment, decrement, and reset its value.
using Microsoft.Azure.DurableFunctions.Extensions.Abstractions; // Assuming necessary using statements
[EntityStartup]
public class CounterEntityStartup : IEntityStartup
{
public void Configure(IEntityBuilder builder)
{
builder.AddEntity();
}
}
public class CounterEntity : IEntity
{
public enum Operation
{
Increment,
Decrement,
Reset,
Get
}
private int currentValue = 0;
public Task
// In a client or orchestrator function
var entityId = new EntityId("CounterEntity", "myCounter"); // "myCounter" is the unique entity ID
// Increment the counter
await client.SignalEntityAsync(entityId, CounterEntity.Operation.Increment);
// Get the current value
int currentValue = await client.CallEntityAsync(entityId, CounterEntity.Operation.Get);
Console.WriteLine($"Current counter value: {currentValue}");
For detailed information and advanced scenarios, refer to the official Azure Durable Functions documentation: