Skip to content

biellts/universidade-automatiza / .claude/skills/ef-core

ef-core

Verified

Get best practices for Entity Framework Core

FileKindSize
SKILL.mdskill md3.5 KB
---
name: ef-core
description: 'Get best practices for Entity Framework Core'
---

> Neste projeto prevalece `AGENTS.md` → "Acesso a dados":
> - PostgreSQL 17 da aplicação, EF Core 10 + Npgsql. Cada módulo tem o próprio `DbContext` (herda `ModuloDbContext`) e o próprio schema; nunca mapeie tabela de outro módulo.
> - O schema nasce e evolui por **migrations** do EF Core (skill `backend-criar-mapping-ef-core`): `dotnet ef migrations add {Nome} --project src/apps/Automatiza.Modules.{Modulo} --output-dir DataBase/Migrations`. Revise o SQL e nunca edite migration que já está na `main`. `EnsureCreated`/`EnsureDeleted` só em teste.
> - Nomes em snake_case pela convenção `UseSnakeCaseNamingConvention()`; `ToTable` explícito no plural; sem `HasColumnName` coluna a coluna.
> - EF Core só grava agregados, com um único `SaveChanges` por operação; leitura é Dapper; teste unitário é só de domínio, sem DbContext.

# Entity Framework Core Best Practices

Your goal is to help me follow best practices when working with Entity Framework Core.

## Data Context Design

- Keep DbContext classes focused and cohesive (um por módulo, só com os agregados do módulo)
- Use constructor injection for configuration options
- Override OnModelCreating for fluent API configuration (o `ModuloDbContext` já aplica o schema e os `IEntityTypeConfiguration<T>` do assembly)
- Separate entity configurations using IEntityTypeConfiguration

## Entity Design

- Ids `Guid` gerados no domínio (`Guid.CreateVersion7()`), mapeados com `ValueGeneratedNever()`
- Implement proper relationships (one-to-one, one-to-many, many-to-many) — só dentro do módulo; referência a outro módulo é apenas o Id
- Use fluent API for constraints; no data annotations on domain entities
- Implement appropriate navigational properties
- Value objects use `ComplexProperty` (see skill `backend-criar-value-object`)
- Enums `: short` com `HasConversion<short>()`; datas `DateTimeOffset` (`timestamptz`, UTC)

## Migrations

- Uma migration por mudança, com nome descritivo em PascalCase
- Revise o SQL gerado (`dotnet ef migrations script`) antes do PR
- Nunca edite uma migration que já está na `main`: crie outra
- Restrições únicas e índices declarados no mapeamento viram parte da migration — unicidade é garantida pelo banco

## Loading the aggregate

- Load the aggregate with its collections (`Include`/`AutoInclude`) before changing it
- Avoid N+1 query problems by properly including related data

## Change Tracking & Saving

- Use appropriate change tracking strategies
- One `SaveChanges()` per operation — it is the transaction; no manual transactions
- Implement concurrency control for multi-user scenarios
- Use appropriate DbContext lifetimes (scoped for web apps)
- Auditoria (`CriadoEm`/`ModificadoEm`) é preenchida pelo `AuditoriaInterceptor`; não preencha à mão

## Security

- Avoid SQL injection by using parameterized queries
- Implement appropriate data access permissions
- Be careful with raw SQL queries
- Consider data encryption for sensitive information
- Multiempresa (quando o módulo Empresas existir): filtro global por `tenant_id` + Row-Level Security no PostgreSQL (ADR-003)

## Testing

- Mapping, migrations, transaction and rollback are covered by integration tests (`ApplicationFactory` + Testcontainers PostgreSQL, com as migrations aplicadas na subida), never by mocking DbContext

When reviewing my EF Core code, identify issues and suggest improvements that follow these best practices.
slack-gif-creatoranthropics/skillsKnowledge and utilities for creating animated GIFs optimized for Slack. Provides constraints, validation tools, and animation concepts. Use when users request animated GIFs for Slack like "make me a GIF of X doing Y for Slack."Stars: 198kUpdated Claude CodeCodexVerifiedInstall
ponytailDietrichGebert/ponytailLazy senior dev mode for any coding task: the smallest change that fully solves it, and a reply a busy human understands in one read.Stars: 194kUpdated Claude CodeCodexVerifiedInstall
ponytail-debtDietrichGebert/ponytailHarvest every shortcut: comment into one debt ledger, so deferrals get tracked instead of forgotten. One-shot report.Stars: 194kUpdated Claude CodeCodexVerifiedInstall
ponytail-debtDietrichGebert/ponytailList every `shortcut:` comment (and older `ponytail:` ones) as a debt ledger. One-shot report, changes nothing. Use for "ponytail debt", "what did ponytail defer", "list the shortcuts", /ponytail-debt.Stars: 194kUpdated Claude CodeCodexVerifiedInstall