agentleFS
Sorcha-PlatformSorcha-Platform/Sorcha/.claude/skills/entity-framework/SKILL.md

entity-framework

Skill2 starsChanged 10 months agoMITView on GitHub

Handles Entity Framework Core database access, migrations, and repository patterns for PostgreSQL. Use when: Creating DbContext classes, writing migrations, implementing repositories, configuring entity relationships, or optimizing database queries.

The file

We split this skill into the rules it gives an agent

1 rule. About 0 are common, 1 is distinctive, and 0 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈1

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 0

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    Verify the single migration is in sync with the model: before relying on it (no need to regenerate if clean):

    line 43

≈ “Common” is an estimate: at least 1 in 5 of the 213,897 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Entity Framework Core Skill

Sorcha uses EF Core 9+ with PostgreSQL (Npgsql) as the primary relational data store. The codebase uses service-specific repositories (each a focused interface + a concrete EF Core implementation — there is no generic IRepository<T> base), soft delete via query filters, and automatic migrations on startup.

Quick Start

Register DbContext with PostgreSQL

// src/Services/Sorcha.Wallet.Service/Extensions/WalletServiceExtensions.cs (AddWalletDatabase)
services.AddDbContext<WalletDbContext>((sp, options) =>
{
    var dataSource = sp.GetRequiredService<NpgsqlDataSource>();
    options.UseNpgsql(dataSource, npgsql =>
    {
        npgsql.EnableRetryOnFailure(maxRetryCount: 10, maxRetryDelay: TimeSpan.FromSeconds(30), errorCodesToAdd: null);
        npgsql.MigrationsHistoryTable("__EFMigrationsHistory", "wallet");
    });
});

Create a Migration

# From project directory containing DbContext
dotnet ef migrations add InitialSchema --project src/Core/Sorcha.Wallet.Core --startup-project src/Services/Sorcha.Wallet.Service

Clean-start migration convention (pre-release, no data preservation)

This repo is pre-release and does not preserve existing data across schema changes. The convention is to squash all migrations into a single InitialCreate per service rather than accumulate incremental migrations — fold the new schema into the existing *_InitialCreate.cs + .Designer.cs + *ModelSnapshot.cs, keeping the same migration ID (don't regenerate the timestamp). Every environment re-creates its DB (down -v) to pick up the change. (E.g. Sorcha.Blueprint.Service absorbed the F142 RehearsalPass migration and the F145 +LastAppliedTxId / −IsReadOnlyMirror change into one …_InitialCreate.)

Implications:

  • A plain image swap is NOT enough for a schema change on a standing node — MigrateAsync sees the InitialCreate ID already applied and skips it, so the new column never lands (symptom: column "X" of relation "Y" does not exist). Recreate the DB (down -v, or drop+recreate the one database) on existing nodes. A fresh-volume node is fine — it applies the full InitialCreate.
  • Verify the single migration is in sync with the model before relying on it (no need to regenerate if clean):
dotnet ef migrations has-pending-model-changes \
  --project src/Services/Sorcha.Blueprint.Service --startup-project src/Services/Sorcha.Blueprint.Service
# "No changes have been made to the model since the last migration." = in sync, nothing to squash.

Apply Migrations Programmatically

// Startup pattern used in Sorcha services
var pending = await dbContext.Database.GetPendingMigrationsAsync();
if (pending.Any())
    await dbContext.Database.MigrateAsync();

Key Concepts

ConceptUsageExample
DbContextSchema definition + change trackingWalletDbContext, TenantDbContext
RepositoryData access abstractionEFCoreRepository<T, TId, TContext>
Soft DeleteQuery filter on DeletedAt.HasQueryFilter(e => e.DeletedAt == null)
JSONBPostgreSQL JSON columns.HasColumnType("jsonb")
ExecuteUpdateBulk updates without loadingExecuteUpdateAsync(s => s.SetProperty(...))

Common Patterns

Repository with Optional Eager Loading

// src/Core/Sorcha.Wallet.Core/Repositories/EfCoreWalletRepository.cs
public async Task<WalletEntity?> GetByAddressAsync(string address, bool includeAddresses = false)
{
    IQueryable<WalletEntity> query = _context.Wallets;
    
    if (includeAddresses)
        query = query.Include(w => w.Addresses);
    
    return await query.AsNoTracking().FirstOrDefaultAsync(w => w.Address == address);
}

Soft Delete with Filter Bypass

// Bypass query filter for admin operations
var deleted = await _context.Wallets
    .IgnoreQueryFilters()
    .FirstOrDefaultAsync(w => w.Address == address);

See Also

  • patterns - DbContext configuration, entity mapping, query optimization
  • workflows - Migration commands, testing patterns, deployment

Related Skills

  • See the postgresql skill for connection configuration and PostgreSQL-specific features
  • See the aspire skill for service registration and health checks
  • See the xunit skill for testing DbContext with InMemory provider

Documentation Resources

Fetch latest EF Core documentation with Context7.

Library ID: /dotnet/entityframework.docs

Recommended Queries:

  • "DbContext pooling configuration dependency injection"
  • "migrations code-first apply production deployment"
  • "query filters soft delete global filters"
  • "bulk operations ExecuteUpdate ExecuteDelete"

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.