DEV Community

Cover image for An EF Core-Inspired ORM for Rust: Change Tracking, Not Just SQL
Start
Start

Posted on Edited on

An EF Core-Inspired ORM for Rust: Change Tracking, Not Just SQL

Most Rust ORM discussions start with SQL generation. Can it produce a window function? Does it support LATERAL? How many queries for this join?

Those questions matter. They are also not where most business code breaks.

The code that breaks is usually a partial update that overwrites a concurrent change.

Or a migration that cannot run on an existing database. Or a transaction that commits half the work.

None of those failures makes noise in a unit test.

rust-ef 2.9.1 takes the EF Core model and aims at those problems: a DbContext, explicit change tracking, transactions, and migrations.

The entity owns its schema

An entity and its configuration live together:

#[derive(EntityType)]
#[table("orders")]
pub struct Order {
    #[primary_key]
    pub id: String,
    pub tenant_id: String,
    pub status: String,
    #[concurrency_check]
    pub version: i64,
}

pub struct OrderConfiguration;
#[entity(Order)]
impl IEntityTypeConfiguration<Order> for OrderConfiguration {
    fn configure(&self, builder: &mut EntityTypeBuilder<'_, Order>) {
        builder.has_index(&[Order::COLUMN_TENANT_ID, Order::COLUMN_STATUS]);
    }
}
Enter fullscreen mode Exit fullscreen mode

The point is not the attribute syntax. It is that the schema is declared next to the type that uses it, and the migration tool can read it.

If the table is created by hand-written SQL, the next environment will drift. That drift is invisible until a query fails in staging.

Queries are typed, but writes are tracked

A list query uses a Predicate and a paginated terminal:

let predicate = Predicate::<Order>::always()
    .and(linq!(|o: Order| o.tenant_id == tenant))
    .and_opt(keyword.map(|k| linq!(|o: Order| o.no.contains(k))));

let page = ctx.set::<Order>().query()
    .filter(predicate)
    .order_by_field_desc(Order::created_at)
    .then_by_field_desc(Order::id)
    .to_page(&paging)
    .await?
    .map_items(OrderModel::from);
Enter fullscreen mode Exit fullscreen mode

A command does not call UPDATE with every column. It edits the tracked entity, lets the context detect changes, and saves:

ctx.edit(order, |o| o.patch(req))?;
ctx.detect_changes();
ctx.save_changes().await?;
Enter fullscreen mode Exit fullscreen mode

detect_changes writes only the dirty columns.

That matters when two people edit the same order: a full-row update overwrites the other person's change even if the fields do not overlap.

The cost is that you have to load the entity first.

For a bulk status update over 100,000 rows, that is the wrong tool.

rust-ef has execute_update for that case, and it bypasses change tracking and interceptors on purpose.

Transactions and error mapping are boundaries

ctx.use_transaction(|ctx| async move {
    ctx.add(order);
    ctx.save_changes().await?;
    Ok(())
}).await?;
Enter fullscreen mode Exit fullscreen mode

The transaction boundary is explicit.

So is the error boundary.

EFError implements From<EFError> for AppError, so a handler can use ? and let the framework map unique violations, concurrency conflicts, and connection failures.

There is no rust-webx feature and no bridge crate. rust-ef does not depend on the web framework.

That keeps the ORM usable in a worker or a CLI, and it removes a whole class of version coupling.

What it does not do

This is not EF Core parity, and it does not try to be.

Complex reporting still needs typed projections (select_items, to_list_rows) or the raw SQL escape hatch.

Migrations still need a plan for SQLite's limited ALTER TABLE.

The persistence adapters for auth, outbox, idempotency, AI usage, and payment inbox live in the framework repository under examples/adapters/*/ef.

They are publish = false and meant to be copied, not depended on.

That last point is easy to miss. If you add rust-webx-pay-ef to Cargo.toml, it will not resolve. The table and the adapter belong to your service.

Try it on one aggregate

Do not migrate the whole schema first.

Pick one aggregate with a real state transition.

Write the entity and its configuration. Replace one read with Predicate + to_page. Replace one write with edit + detect_changes + save_changes.

Then run the migration diff against a copy of the database.

If the diff is empty on the first try, the model and the schema agree. If it is not, you have found the drift before production did.

Repository: https://github.com/Rust-Framework/rust-ef

Top comments (0)