---
title: "Store LLM run state in Entity Framework Core with C#"
url: https://recursiveai.org/onellm/cookbook/persist-agent-state-to-ef-core/
description: "Store LLM run state in Entity Framework Core with C#. Run OneLLM offline, save its state to SQLite, then reload the conversation by ID."
version: "1.0.1"
---

# Store LLM run state in Entity Framework Core with C#

**OneLLM** is a free, open-source LLM and agent library for .NET from Recursive AI. MIT or Apache-2.0, no native dependencies.

[NuGet](https://www.nuget.org/packages/RecursiveAI.OneLlm.EntityFrameworkCore) · [GitHub](https://github.com/recursive-ai-oss/onellm-csharp) · [Docs](https://recursiveai.org/onellm/docs/) · [Download example (.zip)](https://recursiveai.org/onellm/cookbook/persist-agent-state-to-ef-core/persist-agent-state-to-ef-core.zip)

An instance is a saved run: the conversation and its state. Use `EfInstanceStore` to reload it by ID.

```shell
dotnet add package RecursiveAI.OneLlm.EntityFrameworkCore
dotnet add package Microsoft.EntityFrameworkCore.Sqlite
```

Requires [.NET 10](https://dotnet.microsoft.com/download/dotnet/10.0) (net10.0); .NET 9 and earlier aren’t supported.

```csharp
using Microsoft.EntityFrameworkCore;
using OneLlm;
using OneLlm.Definitions;
using OneLlm.EntityFrameworkCore;
using OneLlm.Messages;
using OneLlm.Testing;

var options =
    new DbContextOptionsBuilder<AppDb>()
    .UseSqlite("Data Source=runs.db").Options;
await using (var db = new AppDb(options))
    await db.Database.EnsureCreatedAsync();

var runtime = new Runtime
{
    Store = new EfInstanceStore(
        () => new AppDb(options))
};
var model = new ScriptedProvider("openai");
model.EnqueueText("The answer is four.");
runtime.Providers.Set("openai", model);
var result = await runtime.RunAgentAsync(
    new AgentDefinition
    {
        Name = "math",
        Model = "gpt-6-luna",
        InitialPrompts =
            [Message.FromUser("What is 2 + 2?")]
    });

var reader = new EfInstanceStore(
    () => new AppDb(options));
var saved = await reader.LoadAsync(
    result.Instance.InstanceId);
if (saved is null)
    throw new Exception("Missing saved run.");
Console.WriteLine(saved.State);
Console.WriteLine(
    saved.Messages[^1].GetAssistantText());

sealed class AppDb(DbContextOptions<AppDb> options)
    : DbContext(options)
{
    protected override void OnModelCreating(
        ModelBuilder model)
        => model.ApplyOneLlm();
}
```

You don’t need an input file: the prompt and scripted reply are in the code. The SQLite provider creates `runs.db` in the working directory. OneLLM has no native dependencies, but the SQLite provider in this example ships a native SQLite library. `waiting` means the run finished its turn and is waiting for input. If you try to load an unknown ID, `LoadAsync` returns `null`.

`ScriptedProvider` is the offline stand-in from `OneLlm.Testing`; `gpt-6-luna` selects the scripted route in this example, not a live model. To register a real provider, see [Call Ollama from C#](https://recursiveai.org/onellm/cookbook/call-ollama-from-csharp/#variations).

Unzip [the example](https://recursiveai.org/onellm/cookbook/persist-agent-state-to-ef-core/persist-agent-state-to-ef-core.zip), then `dotnet run`.

Writes `runs.db` and prints the state and reply loaded through a new store:

```text
waiting
The answer is four.
```

## Variations

**Find the latest waiting run.** Add this before the `AppDb` declaration. This reads from the same database; it doesn’t ask the model again.

```csharp
var query = new OneLlm.Instances.InstanceQuery
{
    State = "waiting", Limit = 1
};
await foreach (var entry in reader.ListAsync(query))
    Console.WriteLine($"{entry.Name}: {entry.State}");
```

```text
math: waiting
```

## Related recipes

- [Save and resume a chat](https://recursiveai.org/onellm/cookbook/save-and-resume-a-chat/)
- [Log LLM run events to a JSONL file](https://recursiveai.org/onellm/cookbook/capture-llm-run-events-as-jsonl/)

## The short answer

Call `ApplyOneLlm()` in your `DbContext` and give `EfInstanceStore` a factory that creates a fresh context. Set that store on the runtime before starting a run. Keep its instance ID so you can reload the same instance later. The factory only needs to know how to connect to the same database; it doesn’t need the original runtime or a model connection to load the saved data.

## How do you store LLM conversation history in EF Core?

Keep the conversation as part of the saved instance if you want to recover the conversation *and* the run that produced it. The store keeps one row per instance, not one EF entity per message. Loading the row gives you the current messages and state together. If all your application needs is to display the last reply, you can read it directly without making a new model call, as in the example. To get a list of runs for a picker or status page, use `ListAsync` for summaries and `LoadAsync` only for the one the user selects.

The ID identifies the instance, not the person who started it. In a multi-user app, keep the association between your own user or conversation ID and the OneLLM instance ID in your app’s data. Starting a new run and loading an existing run by ID are different operations; matching the old run’s name won’t restore its messages.

## How do you add the tables with EF Core migrations?

[`ApplyOneLlm()`](https://recursiveai.org/onellm/docs/stores/#entity-framework-core) maps `OneLlmInstances`, `OneLlmRecords`, and `OneLlmLeases`. It doesn’t install a database provider or ship migrations, so choose a provider and include the mapping in your app’s own migrations. The example calls `EnsureCreatedAsync` for a new example database. In an existing migrations-based app, add and apply a migration instead: Microsoft’s [EF Core schema guidance](https://learn.microsoft.com/en-us/ef/core/managing-schemas/ensure-created) warns against mixing `EnsureCreatedAsync` and migrations.

Use a factory that returns a new context on each call rather than passing a single shared context to the store. If two saves race on the same instance, the version field lets the store retry; the last save wins. The store doesn’t merge two edits to the same conversation.

## What’s the difference between saved state and run history?

The instance row is a snapshot of the latest state. The records table is for the sequence of events that led there. Mapping both tables doesn’t enable event logging: register `EfRecordSink` separately if you want the runtime to write records into your `DbContext`. If you need only to pick up a conversation where it left off, the instance store is enough.
