> For the complete documentation index, see [llms.txt](https://framework.aic.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://framework.aic.io/technical-guidelines-code-standards-and-tech-stack/data-and-persistence-standards/ef-core-standards.md).

# EF Core Standards

## Purpose

EF Core is an approved secondary persistence technology for AIC systems where a relational database is the right architectural choice. MongoDB remains the default primary persistence layer.

EF Core is powerful but must be used deliberately. AIC standards prevent hidden performance issues, migration risk, and accidental API leakage.

## Mandatory Rules

* Do not return EF entities directly from public APIs.
* Do not use lazy loading by default.
* Use async database calls.
* Pass cancellation tokens.
* Use migrations under source control.
* Review important generated SQL.
* Keep `DbContext` scoped.
* Avoid long-lived `DbContext` instances.
* Use transactions where consistency requires them.

## DbContext Registration

```csharp
services.AddDbContext<ApplicationDbContext>(options =>
{
    options.UseSqlServer(connectionString);
});
```

Use pooling only after reviewing state and tenant implications.

## Entity Configuration

Prefer explicit configuration:

```csharp
public sealed class CaseRecordConfiguration : IEntityTypeConfiguration<CaseRecord>
{
    public void Configure(EntityTypeBuilder<CaseRecord> builder)
    {
        builder.ToTable("Cases");
        builder.HasKey(x => x.Id);
        builder.Property(x => x.Reference).IsRequired().HasMaxLength(50);
        builder.Property(x => x.CreatedAtUtc).IsRequired();
    }
}
```

## Query Rules

* Project only required fields.
* Use `AsNoTracking` for read-only queries.
* Avoid client-side evaluation surprises.
* Avoid N+1 queries.
* Limit result sets.
* Use pagination.
* Index columns used for filtering and sorting.

## Save Rules

* Validate before persistence.
* Use transactions for multi-aggregate consistency where necessary.
* Handle concurrency exceptions.
* Capture audit fields consistently.
* Do not hide database failures.

## Migration Checklist

* Migration reviewed by developer and database-aware reviewer.
* Destructive change identified.
* Rollback or fix-forward approach documented.
* Data migration risk assessed.
* Index impact assessed.
* Production deployment order understood.
