# EntityState

`EntityState<TKey, TEntity>` is an immutable collection of entities with unique ids. It keeps insertion order and looks entities up by id without scanning. Entities implement `IEntity<TKey>`.

Source: https://github.com/phmatray/Ducky/blob/v2/test/Ducky.Docs.Tests/Core/EntityStateGuideTests.cs#L7-L34

```csharp
public sealed record TodoItem(int Id, string Title, bool Done) : IEntity<int>;

public sealed record Todos(EntityState<int, TodoItem> Items)
{
    // The same Todos when the collection is the same instance, so an unchanged collection commits nothing.
    public Todos With(EntityState<int, TodoItem> items) => ReferenceEquals(items, Items) ? this : new(items);
}

public sealed record TodoAdded(TodoItem Todo);

public sealed record TodoToggled(int Id);

public sealed record TodoRemoved(int Id);

public sealed record TodosLoaded(ImmutableList<TodoItem> Todos);

public sealed class TodosSlice : Slice<Todos>
{
    public TodosSlice()
    {
        On<TodoAdded>((state, action) => state.With(state.Items.Upsert(action.Todo)));
        On<TodoToggled>((state, action) => state.With(state.Items.Update(action.Id, todo => todo with { Done = !todo.Done })));
        On<TodoRemoved>((state, action) => state.With(state.Items.Remove(action.Id)));
        On<TodosLoaded>((state, action) => state.With(state.Items.Merge(action.Todos, MergeStrategy.PreferIncoming)));
    }

    protected override Todos Initial => new(EntityState<int, TodoItem>.Empty);
}
```

Every operation returns a new collection, or the same instance when nothing changed:

| Operation | Returns the same instance when |
|---|---|
| `Upsert(entities)` | every entity is the stored one (same reference) |
| `Update(id, update)` | the id is missing, or `update` returned the same entity |
| `Map(map)` | no entity changed |
| `Remove(ids)` | nothing was removed |

`Add` throws `ArgumentException` for an id that exists, and so does the constructor for duplicate ids. `Merge(entities, strategy)` combines a batch with the stored entities: `PreferIncoming` replaces the stored ones, `PreferExisting` keeps them, `FailIfDuplicate` throws. `SetAll` replaces everything, `RemoveWhere` removes by predicate.

Keeping the instance matters because the store compares references: `Todos.With` above returns the same `Todos` when the collection didn't change, so toggling a missing id commits nothing and notifies nobody.

## Read

Source: https://github.com/phmatray/Ducky/blob/v2/test/Ducky.Docs.Tests/Core/EntityStateGuideTests.cs#L53-L56

```csharp
var todos = store.State.Get<Todos>().Items;
var first = todos.Find(1);                         // by id, without scanning
var exists = todos.Contains(3);                    // false: removed
var open = todos.Items.Count(todo => !todo.Done); // Items keeps insertion order
```

Only `Items` is serialized: `Count` and the id index are rebuilt, never stored.
