Drn entityframework

From duranserkan/DRN-Project · View interactive version

Drn entityframework is an AI agent skill from the GitHub repository duranserkan/DRN-Project. Configure DRN PostgreSQL contexts, identity tracking, migrations, prototype safety, repositories and cancellation.

How to use this skill

Skill file

DRN.Framework.EntityFramework

Read the installed DRN.Framework.EntityFramework package README for connection examples, attribute hooks and provider defaults. Locate the package

DrnContext Pattern

DRNSTRUCTURE003 infers conventional repository and migration destinations from the context namespace and logical source home, including Compile/Link and split-role prefixes. Context partials and associated artifacts must agree with that layout. Alternate or ambiguous destinations require explicit metadata, with a Reason for alternatives. Repository inference applies to aggregate DbSets, including inherited sets. Migration inference applies to associated migration/snapshot artifacts. Explicit destinations are validated even without artifacts. Empty contexts need no metadata. Prefer matching context names, subdomain namespaces and folders over alias mappings.

Use immediate Repositories, Configurations and Migrations folders and matching final namespace segments for Infra repository implementations, EF configurations and DRN migrations/snapshots. Configuration classes end in Config. Domain repository interfaces stay beside their aggregates. Custom Npgsql options applied to a context start with its exact name and end in Options before an optional Attribute. Prefer QAContextNpgsqlDbContextOptionsAttribute, including NpgsqlDbContext in the name. Concrete, closed DRN contexts must directly apply a custom NpgsqlDbContextOptionsAttribute descendant. Inherited options and framework defaults do not replace that declaration. Framework defaults remain exempt from naming checks. DRNSTRUCTURE006, DRNSTRUCTURE007 and DRNPERSISTENCE009 own folder/options checks. Destination override reasons do not waive them.

For each aggregate assigned to an Infra context, provide a concrete SourceKnownRepository<TContext,TEntity> implementing its Domain subdomain's repository interface. One implementation can serve multiple contexts in that Infra. Merely referencing a Domain project does not require all its repositories. DRNREPOSITORY004 uses DbSets, explicit inclusion and supported configuration evidence, respecting exclusion/Ignore. See aggregate naming and contracts.

Expose only AggregateRoot descendants through instance DbSet<TEntity> properties on DrnContext<TContext>. DRNPERSISTENCE008 includes inherited properties and closed generic substitutions. Keep child entities behind aggregate boundaries. This rule excludes the separate DrnContextIdentity hierarchy and does not change EF mapping or Set/GetEntities constraints.

Use DrnContext<TContext> for the standard DRN runtime pattern. Provide the options constructor and parameterless constructor for migrations. Register via attribute scanning. Use the context type name for its connection-string key. Put entity configurations in the same assembly, in the context namespace or a child namespace.

Application conventions require concrete application-owned EF contexts to implement IDrnContext, directly or through inheritance. Use a narrow justified DRNPERSISTENCE007 exception for specialized contexts. The interface alone does not establish provider, model or lifecycle correctness. Consult SharedKernel's installed CONVENTIONS.md for architecture rules and exceptions.

DRN design-time factories require an exact public DbContextOptions<TContext>-only constructor. For observed EF registrations of non-DRN contexts, DRNPERSISTENCE001 also accepts non-generic DbContextOptions and additional injected dependencies. A model override that only forwards to the framework base retains its namespace-filtered configuration scan evidence.

[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
public class OrdersContextNpgsqlDbContextOptionsAttribute : NpgsqlDbContextOptionsAttribute
{
    // Empty keeps framework defaults. Override hooks such as ConfigureNpgsqlOptions, ConfigureDbContextOptions or SeedAsync to customize this context.
}

[OrdersContextNpgsqlDbContextOptions]
public class OrdersContext : DrnContext<OrdersContext>
{
    public OrdersContext(DbContextOptions<OrdersContext> options) : base(options) { }
    public OrdersContext() : base(null) { }
    public DbSet<OrderEntity> Orders { get; set; }
}

Scan the application's context assembly with builder.Services.AddServicesWithAttributes(typeof(OrdersContext).Assembly). The named connection is ConnectionStrings:OrdersContext. DRN Hosting runs startup validation. Standalone hosts must integrate the framework's startup validation lifecycle explicitly.

Augmented Entity Behavior

| Feature | Public behavior |

|---|---|

| Identity and lifecycle | Tracking assigns missing internal IDs. Saving initializes external identity, conversion operations, timestamps and lifecycle hooks. Queried entities support ID operations. An assigned ID does not prove persistence. |

| ID conversion | Entity and repository ToSecure / ToPlain are idempotent. |

| JSON models | IEntityWithModel<T>.Model maps to jsonb. |

| Identity naming | ASP.NET Core Identity tables and columns use snake_case. |

| Inheritance | TPH/TPT/TPC mappings share root keys and properties. Each concrete entity retains its own entity-type metadata. |

| Validation | Concrete, effectively non-private entities need unique (EntityType, AppId) pairs. Abstract types and types enclosed by a private type are excluded. Different partitions may reuse an entity byte. |

Concurrent ID generators in the same partition need distinct instance IDs. Pending model changes fail startup validation even when auto-migration is disabled, unless prototype recreation handles them.

Connection String Conventions

| Environment | Connection source |

|---|---|

| Production or Staging | Explicit ConnectionStrings:{ContextName}. Development keys are ignored. |

| Local Development with Testcontainers | Enable LaunchExternalDependencies and invoke the launch hook. PostgresContainerSettings supplies container settings. |

| Containerized Development | DrnContextDevelopmentConnection builds the connection from postgres-password and DrnContext_Dev* settings. |

| Integration tests | Bind ContainerContext.Postgres to the test application. Start RabbitMQ explicitly when needed. |

In Development, an explicit named connection takes precedence. Without a named connection or the development password, resolution fails.

Migrations

Compose attribute SeedAsync after any custom EF seeding callback. Keep seeds idempotent and use the same scoped context. Eligible automatic startups call MigrateAsync even with zero pending migrations. Migration operations run seeds under the EF migration lock and a later startup may retry failed seeding. Explicit DI migration/creation calls seed too. Design-time contexts without DI omit attribute seeding. Prototype creation has no migration-lock guarantee.

Use the context project for design-time startup. Resolve migration commands from the profile and follow the exact-command approval gate. The package README owns option-hook composition.

Prototype Mode

Prototype recreation drops the database. Allow it only in Development with all of the following:

Staging can opt into migrations through AutoMigrateStaging. Production never auto-migrates. Neither environment permits prototype recreation.

Entity Configuration

SourceKnownPersistenceAttribute is descriptive convention evidence only. It does not include or exclude an entity in the EF model. Attribute-only mapping needs no configuration class or suppression. The additive configuration refactoring declines uncertain discovery and collisions. Multiple contexts can share one subdomain. Keep cross-owner suppression separate from membership, and preserve context names and storage identity. Consult SharedKernel's installed convention guide for current tooling limits. Namespace normalization still requires model/snapshot compatibility evidence.

Prefer attributes for ordinary mappings. Use Fluent API for complex relationships. Configure the relationship before navigation options such as AutoInclude(). EF Core ordering example

Use NpgsqlDbContextOptionsAttribute for provider, data source, context and seed hooks. DrnContextDefaults applies DRN conventions. Consult the EntityFramework README before overriding pooling, buffers, timeouts and statement preparation through a performance settings attribute.

RepositorySettings

Build custom queries from EntitiesWithAppliedSettings() to preserve filters, tracking and auto-include policy. Use named filters for repository-wide conditions. Public CRUD, query and pagination methods are virtual. Protected pagination overloads are not.

GUID methods validate the declared entity type and partition, including secondary partitions. The configured default resolves in the parser. Keep Plain/Auto overrides under application control and accept parsed records only from trusted callers. Undefined GUID formats reject nulls and empty batches. Enumerable helpers validate when enumerated. Record and entity inputs have no format argument. Keep mixed-format batch deletes atomic on rejection. SharedKernel validation

Repository Cancellation

Settings.ScopeKey selects the cancellation group. The default null uses Utils.Cancellation.Root, so CancelChanges() affects all scope-wide operations. A CancellationScopeKey selects a child shared by repositories with that key. CancellationToken, CancelWhen(token) and CancelChanges() use the selected group.

repository.Settings.ScopeKey = CancellationScopeKey.For<UserRepository>("shared-writes");

using var operationSource =
    CancellationTokenSource.CreateLinkedTokenSource(
        repository.CancellationToken,
        operationToken);

For one operation, dispose the local linked source after the work completes. For group ownership, see scoped cancellation.

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.