[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M79XDPTJJ7NB7HF36DPZBD6J":3,"skill-same:01M79XDPTJJ7NB7HF36DPZBD6J":47},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":27,"repositoryHtmlUrl":28,"repositoryHomepageUrl":6,"ownerHtmlUrl":29,"ownerBlogUrl":30,"ownerDescription":31,"updatedAt":32,"install":33,"resources":46},"01M79XDPTJJ7NB7HF36DPZBD6J","deniz-dotnet-general.efcore-patterns",null,"Entity Framework Core best practices including NoTracking by default, query splitting for navigation collections, migration management, dedicated migration services, and common pitfalls to avoid.","Blind-Striker\u002Fagent-skills-and-plugins","Blind-Striker","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F1965259?v=4","01M79WFXTE5PH0C1VB7B54ANMN","Deniz İrgin","01M79WFXV5KZ5GST1K8G035DM5",1,"MIT","https:\u002F\u002Fgithub.com\u002FBlind-Striker\u002Fagent-skills-and-plugins\u002Fblob\u002Fmaster\u002Fopencode\u002Fdeniz-dotnet-general\u002Fskills\u002Fdeniz-dotnet-general.efcore-patterns\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: deniz-dotnet-general.efcore-patterns\ndescription: Entity Framework Core best practices including NoTracking by\n  default, query splitting for navigation collections, migration management,\n  dedicated migration services, and common pitfalls to avoid.\n---\n\n# Entity Framework Core Patterns\n\n## When to Use This Skill\n\nUse this skill when:\n- Setting up EF Core in a new project\n- Optimizing query performance\n- Managing database migrations\n- Integrating EF Core with .NET Aspire\n- Debugging change tracking issues\n- Loading multiple navigation collections efficiently (query splitting)\n\n## Core Principles\n\n1. **NoTracking by Default** - Most queries are read-only; opt-in to tracking\n2. **Never Edit Migrations Manually** - Always use CLI commands\n3. **Dedicated Migration Service** - Separate migration execution from application startup\n4. **ExecutionStrategy for Retries** - Handle transient database failures\n5. **Explicit Updates** - When NoTracking, explicitly mark entities for update\n\n---\n\n## Pattern 1: NoTracking by Default\n\nConfigure your DbContext to disable change tracking by default. This improves performance for read-heavy workloads.\n\n```csharp\npublic class ApplicationDbContext : DbContext\n{\n    public ApplicationDbContext(DbContextOptions\u003CApplicationDbContext> options)\n        : base(options)\n    {\n        \u002F\u002F Disable change tracking by default for better performance on read-only queries\n        \u002F\u002F Use .AsTracking() explicitly for queries that need to track changes\n        ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;\n    }\n\n    public DbSet\u003COrder> Orders => Set\u003COrder>();\n    public DbSet\u003CCustomer> Customers => Set\u003CCustomer>();\n}\n```\n\n### When NoTracking is Active\n\n**Read-only queries work normally:**\n```csharp\n\u002F\u002F ✅ Fast read - no tracking overhead\nvar orders = await dbContext.Orders\n    .Where(o => o.Status == OrderStatus.Pending)\n    .ToListAsync();\n```\n\n**Writes require explicit handling:**\n```csharp\n\u002F\u002F ❌ WRONG - Entity not tracked, SaveChanges does nothing\nvar order = await dbContext.Orders.FirstOrDefaultAsync(o => o.Id == orderId);\norder.Status = OrderStatus.Shipped;\nawait dbContext.SaveChangesAsync(); \u002F\u002F Nothing happens!\n\n\u002F\u002F ✅ CORRECT - Explicitly mark entity for update\nvar order = await dbContext.Orders.FirstOrDefaultAsync(o => o.Id == orderId);\norder.Status = OrderStatus.Shipped;\ndbContext.Orders.Update(order); \u002F\u002F Marks entire entity as modified\nawait dbContext.SaveChangesAsync();\n\n\u002F\u002F ✅ ALSO CORRECT - Use AsTracking() for the query\nvar order = await dbContext.Orders\n    .AsTracking()\n    .FirstOrDefaultAsync(o => o.Id == orderId);\norder.Status = OrderStatus.Shipped;\nawait dbContext.SaveChangesAsync(); \u002F\u002F Works!\n```\n\n### When to Use Tracking\n\n| Scenario | Use Tracking? | Why |\n|----------|---------------|-----|\n| Display data in UI | No | Read-only, no updates |\n| API GET endpoints | No | Returning data, no mutations |\n| Update single entity | Yes or explicit Update() | Need to save changes |\n| Complex update with navigation | Yes | Tracking handles relationships |\n| Batch operations | No + ExecuteUpdate | More efficient |\n\n### Explicit Add\u002FUpdate Pattern\n\n```csharp\npublic class OrderService\n{\n    private readonly ApplicationDbContext _db;\n\n    \u002F\u002F CREATE - Always use Add (works regardless of tracking)\n    public async Task\u003COrder> CreateOrderAsync(Order order)\n    {\n        _db.Orders.Add(order);\n        await _db.SaveChangesAsync();\n        return order;\n    }\n\n    \u002F\u002F UPDATE - Explicitly mark as modified\n    public async Task UpdateOrderStatusAsync(Guid orderId, OrderStatus newStatus)\n    {\n        var order = await _db.Orders.FirstOrDefaultAsync(o => o.Id == orderId)\n            ?? throw new NotFoundException($\"Order {orderId} not found\");\n\n        order.Status = newStatus;\n        order.UpdatedAt = DateTimeOffset.UtcNow;\n\n        \u002F\u002F Explicitly mark as modified since DbContext uses NoTracking by default\n        _db.Orders.Update(order);\n        await _db.SaveChangesAsync();\n    }\n\n    \u002F\u002F DELETE - Attach and remove\n    public async Task DeleteOrderAsync(Guid orderId)\n    {\n        var order = new Order { Id = orderId };\n        _db.Orders.Remove(order);\n        await _db.SaveChangesAsync();\n    }\n}\n```\n\n---\n\n## Pattern 2: Never Edit Migrations Manually\n\n**CRITICAL:** Always use EF Core CLI commands to manage migrations. Never:\n- Manually edit migration files (except for custom SQL in `Up()`\u002F`Down()`)\n- Delete migration files directly\n- Rename migration files\n- Copy migrations between projects\n\n### Creating Migrations\n\n```bash\n# Create a new migration\ndotnet ef migrations add AddCustomerTable \\\n    --project src\u002FMyApp.Infrastructure \\\n    --startup-project src\u002FMyApp.Api\n\n# With a specific DbContext (if you have multiple)\ndotnet ef migrations add AddCustomerTable \\\n    --context ApplicationDbContext \\\n    --project src\u002FMyApp.Infrastructure \\\n    --startup-project src\u002FMyApp.Api\n```\n\n### Removing Migrations\n\n```bash\n# Remove the last migration (if not yet applied)\ndotnet ef migrations remove \\\n    --project src\u002FMyApp.Infrastructure \\\n    --startup-project src\u002FMyApp.Api\n\n# NEVER do this:\n# rm Migrations\u002F20240101_AddCustomerTable.cs  # ❌ BAD!\n```\n\n### Applying Migrations\n\n```bash\n# Apply all pending migrations\ndotnet ef database update \\\n    --project src\u002FMyApp.Infrastructure \\\n    --startup-project src\u002FMyApp.Api\n\n# Apply to a specific migration\ndotnet ef database update AddCustomerTable \\\n    --project src\u002FMyApp.Infrastructure \\\n    --startup-project src\u002FMyApp.Api\n\n# Rollback to a previous migration\ndotnet ef database update PreviousMigrationName \\\n    --project src\u002FMyApp.Infrastructure \\\n    --startup-project src\u002FMyApp.Api\n```\n\n### Generating SQL Scripts\n\n```bash\n# Generate SQL script for all migrations\ndotnet ef migrations script \\\n    --project src\u002FMyApp.Infrastructure \\\n    --startup-project src\u002FMyApp.Api \\\n    --output migrations.sql\n\n# Generate idempotent script (safe to run multiple times)\ndotnet ef migrations script \\\n    --idempotent \\\n    --project src\u002FMyApp.Infrastructure \\\n    --startup-project src\u002FMyApp.Api\n```\n\n---\n\n## Pattern 3: Dedicated Migration Service with Aspire\n\nSeparate migration execution from your main application using a dedicated migration service. This ensures:\n- Migrations complete before the app starts\n- Clean separation of concerns\n- Controlled seeding in test environments\n\n### Project Structure\n\n```\nsrc\u002F\n├── MyApp.AppHost\u002F           # Aspire orchestration\n├── MyApp.Api\u002F               # Main application\n├── MyApp.Infrastructure\u002F    # DbContext and migrations\n└── MyApp.MigrationService\u002F  # Dedicated migration runner\n```\n\n### MigrationService Program.cs\n\n```csharp\nusing MyApp.Infrastructure.Data;\nusing MyApp.MigrationService;\nusing Microsoft.EntityFrameworkCore;\n\nvar builder = Host.CreateApplicationBuilder(args);\n\n\u002F\u002F Add Aspire service defaults\nbuilder.AddServiceDefaults();\n\n\u002F\u002F Add PostgreSQL DbContext\nvar connectionString = builder.Configuration.GetConnectionString(\"appdb\")\n    ?? throw new InvalidOperationException(\"Connection string 'appdb' not found.\");\n\nbuilder.Services.AddDbContext\u003CApplicationDbContext>(options =>\n    options.UseNpgsql(connectionString, npgsqlOptions =>\n        npgsqlOptions.MigrationsAssembly(\"MyApp.Infrastructure\")));\n\n\u002F\u002F Add the migration worker\nbuilder.Services.AddHostedService\u003CMigrationWorker>();\n\nvar host = builder.Build();\nhost.Run();\n```\n\n### MigrationWorker.cs\n\n```csharp\npublic class MigrationWorker : BackgroundService\n{\n    private readonly IServiceProvider _serviceProvider;\n    private readonly IHostApplicationLifetime _hostApplicationLifetime;\n    private readonly ILogger\u003CMigrationWorker> _logger;\n\n    public MigrationWorker(\n        IServiceProvider serviceProvider,\n        IHostApplicationLifetime hostApplicationLifetime,\n        ILogger\u003CMigrationWorker> logger)\n    {\n        _serviceProvider = serviceProvider;\n        _hostApplicationLifetime = hostApplicationLifetime;\n        _logger = logger;\n    }\n\n    protected override async Task ExecuteAsync(CancellationToken stoppingToken)\n    {\n        _logger.LogInformation(\"Migration service starting...\");\n\n        try\n        {\n            using var scope = _serviceProvider.CreateScope();\n            var dbContext = scope.ServiceProvider.GetRequiredService\u003CApplicationDbContext>();\n\n            await RunMigrationsAsync(dbContext, stoppingToken);\n\n            _logger.LogInformation(\"Migration service completed successfully.\");\n        }\n        catch (Exception ex)\n        {\n            _logger.LogError(ex, \"Migration service failed: {Error}\", ex.Message);\n            throw;\n        }\n        finally\n        {\n            \u002F\u002F Stop the application after migrations complete\n            _hostApplicationLifetime.StopApplication();\n        }\n    }\n\n    private async Task RunMigrationsAsync(ApplicationDbContext dbContext, CancellationToken ct)\n    {\n        \u002F\u002F Use execution strategy for transient failure handling\n        var strategy = dbContext.Database.CreateExecutionStrategy();\n\n        await strategy.ExecuteAsync(async () =>\n        {\n            var pendingMigrations = await dbContext.Database.GetPendingMigrationsAsync(ct);\n\n            if (pendingMigrations.Any())\n            {\n                _logger.LogInformation(\"Applying {Count} pending migrations...\",\n                    pendingMigrations.Count());\n\n                await dbContext.Database.MigrateAsync(ct);\n\n                _logger.LogInformation(\"Migrations applied successfully.\");\n            }\n            else\n            {\n                _logger.LogInformation(\"No pending migrations. Database is up to date.\");\n            }\n        });\n    }\n}\n```\n\n### AppHost Configuration\n\n```csharp\nvar builder = DistributedApplication.CreateBuilder(args);\n\nvar postgres = builder.AddPostgres(\"postgres\");\nvar db = postgres.AddDatabase(\"appdb\");\n\n\u002F\u002F Migrations run first, then exit\nvar migrations = builder.AddProject\u003CProjects.MyApp_MigrationService>(\"migrations\")\n    .WaitFor(db)\n    .WithReference(db);\n\n\u002F\u002F API waits for migrations to complete\nvar api = builder.AddProject\u003CProjects.MyApp_Api>(\"api\")\n    .WaitForCompletion(migrations)  \u002F\u002F Key: waits for migrations to finish\n    .WithReference(db);\n```\n\n---\n\n## Pattern 4: ExecutionStrategy for Transient Failures\n\nAlways use `CreateExecutionStrategy()` for operations that might fail transiently:\n\n```csharp\npublic async Task UpdateWithRetryAsync(Guid id, Action\u003COrder> update)\n{\n    var strategy = _dbContext.Database.CreateExecutionStrategy();\n\n    await strategy.ExecuteAsync(async () =>\n    {\n        var order = await _dbContext.Orders\n            .AsTracking()\n            .FirstOrDefaultAsync(o => o.Id == id);\n\n        if (order is null) return;\n\n        update(order);\n        await _dbContext.SaveChangesAsync();\n    });\n}\n```\n\n**Important:** You cannot use `CreateExecutionStrategy()` with user-initiated transactions. If you need transactions with retry:\n\n```csharp\nvar strategy = _dbContext.Database.CreateExecutionStrategy();\n\nawait strategy.ExecuteAsync(async () =>\n{\n    \u002F\u002F Transaction must be INSIDE the strategy callback\n    await using var transaction = await _dbContext.Database.BeginTransactionAsync();\n\n    try\n    {\n        \u002F\u002F ... your operations ...\n        await _dbContext.SaveChangesAsync();\n        await transaction.CommitAsync();\n    }\n    catch\n    {\n        await transaction.RollbackAsync();\n        throw;\n    }\n});\n```\n\n---\n\n## Pattern 5: Bulk Operations with ExecuteUpdate\u002FExecuteDelete\n\nFor bulk operations, use EF Core 7+ `ExecuteUpdateAsync` and `ExecuteDeleteAsync` instead of loading entities:\n\n```csharp\n\u002F\u002F ❌ SLOW - Loads all entities into memory\nvar expiredOrders = await _db.Orders\n    .Where(o => o.ExpiresAt \u003C DateTimeOffset.UtcNow)\n    .ToListAsync();\n\nforeach (var order in expiredOrders)\n{\n    order.Status = OrderStatus.Expired;\n}\nawait _db.SaveChangesAsync();\n\n\u002F\u002F ✅ FAST - Single SQL UPDATE statement\nawait _db.Orders\n    .Where(o => o.ExpiresAt \u003C DateTimeOffset.UtcNow)\n    .ExecuteUpdateAsync(setters => setters\n        .SetProperty(o => o.Status, OrderStatus.Expired)\n        .SetProperty(o => o.UpdatedAt, DateTimeOffset.UtcNow));\n\n\u002F\u002F ✅ FAST - Single SQL DELETE statement\nawait _db.Orders\n    .Where(o => o.Status == OrderStatus.Cancelled && o.CreatedAt \u003C cutoffDate)\n    .ExecuteDeleteAsync();\n```\n\nThese calls execute immediately and bypass the change tracker, so check the whole write workflow:\n\n- Loaded entities keep their old values and snapshots. A later change to the same properties through\n  a tracked entity can overwrite the SQL change, even in one sequential request. Use one coherent\n  tracked save, or keep the set-based path free of tracked copies; a transaction alone does not\n  refresh tracked state.\n- Configured concurrency tokens are not checked. When optimistic concurrency is required, keep the\n  token predicate, the token update, and the affected-row check.\n- Each call executes on its own: a later `SaveChanges` neither batches it nor makes it atomic with\n  audit or outbox writes. Use one save unit, or an explicit shared transaction where atomicity is\n  required.\n- Client-side cascades and `SaveChanges`-based hooks do not run; command interceptors still see the\n  SQL. Keep the domain behavior those hooks carry instead of bypassing it to save queries.\n\n---\n\n## Pattern 6: Compiled Queries on a Hot Path\n\nOn a path that runs the *same* query shape thousands of times over a reused context, EF Core\nalready caches the translation, but it still processes the expression tree and looks up that cache on\nevery call. When the query is already minimal — an indexed lookup or a small projection — and\n`AsNoTracking` buys nothing, that per-call work is the remaining cost. `EF.CompileQuery` \u002F\n`EF.CompileAsyncQuery` compile once and reuse a delegate that bypasses the lookup; they do not make\ndatabase I\u002FO cheaper:\n\n```csharp\nprivate static readonly Func\u003CAppDbContext, int, ProductListItem> GetProduct =\n    EF.CompileQuery((AppDbContext db, int id) =>\n        db.Products.Where(p => p.Id == id)\n                   .Select(p => new ProductListItem(p.Id, p.Name, p.Price))\n                   .First());\n\npublic ProductListItem Lookup(AppDbContext db, int id) => GetProduct(db, id);\n```\n\nThe delegate is `static`, so it compiles once, and takes the `DbContext` plus each parameter as\narguments. Reach for it on endpoints or loops that execute one query shape at very high frequency; it\ndoes nothing for a one-off query, and it is the last thing to try rather than the first — a\nnon-sargable predicate or an N+1 costs far more than translation does. EF Core 9 does not support\n`EF.Parameter` or `EF.Constant` inside a compiled query.\n\n**Verify:** the hot loop's mean time drops with identical results.\n\n---\n\n## Common Pitfalls\n\n### 1. Forgetting to Update When NoTracking\n\n```csharp\n\u002F\u002F ❌ Silent failure - entity not tracked\nvar customer = await _db.Customers.FindAsync(id);\ncustomer.Name = \"New Name\";\nawait _db.SaveChangesAsync(); \u002F\u002F Does nothing!\n\n\u002F\u002F ✅ Explicit update\nvar customer = await _db.Customers.FindAsync(id);\ncustomer.Name = \"New Name\";\n_db.Customers.Update(customer);\nawait _db.SaveChangesAsync();\n```\n\n### 2. N+1 Query Problem\n\n```csharp\n\u002F\u002F ❌ N+1 queries - one query per order\nvar customers = await _db.Customers.ToListAsync();\nforeach (var customer in customers)\n{\n    var orders = customer.Orders; \u002F\u002F Lazy load triggers query\n}\n\n\u002F\u002F ✅ Eager loading - single query\nvar customers = await _db.Customers\n    .Include(c => c.Orders)\n    .ToListAsync();\n```\n\n### 3. Tracking Conflicts with Multiple DbContext Instances\n\n```csharp\n\u002F\u002F ❌ Tracking conflict - entity tracked by different context\nvar order1 = await _db1.Orders.AsTracking().FindAsync(id);\nvar order2 = await _db2.Orders.AsTracking().FindAsync(id);\norder2.Status = OrderStatus.Shipped;\nawait _db2.SaveChangesAsync(); \u002F\u002F May throw or behave unexpectedly\n\n\u002F\u002F ✅ Use single context or detach first\n_db1.Entry(order1).State = EntityState.Detached;\n```\n\n### 4. Not Using Async Consistently\n\n```csharp\n\u002F\u002F ❌ Blocking call in async context\nvar orders = _db.Orders.ToList(); \u002F\u002F Blocks thread\n\n\u002F\u002F ✅ Async all the way\nvar orders = await _db.Orders.ToListAsync();\n```\n\n### 5. Querying Inside Loops\n\n```csharp\n\u002F\u002F ❌ Query per iteration\nforeach (var orderId in orderIds)\n{\n    var order = await _db.Orders.FindAsync(orderId);\n    \u002F\u002F process order\n}\n\n\u002F\u002F ✅ Single query\nvar orders = await _db.Orders\n    .Where(o => orderIds.Contains(o.Id))\n    .ToListAsync();\n```\n\n---\n\n## DbContext Lifetime in DI\n\n### ASP.NET Core (Scoped by Default)\n\n```csharp\n\u002F\u002F Scoped = one instance per HTTP request\nbuilder.Services.AddDbContext\u003CApplicationDbContext>(options =>\n    options.UseNpgsql(connectionString));\n```\n\n### Background Services (Create Scope)\n\n```csharp\npublic class MyBackgroundService : BackgroundService\n{\n    private readonly IServiceProvider _serviceProvider;\n\n    protected override async Task ExecuteAsync(CancellationToken stoppingToken)\n    {\n        \u002F\u002F ✅ Create scope for each unit of work\n        using var scope = _serviceProvider.CreateScope();\n        var dbContext = scope.ServiceProvider.GetRequiredService\u003CApplicationDbContext>();\n\n        \u002F\u002F ... use dbContext ...\n    }\n}\n```\n\n### Actors \u002F Long-Lived Objects (Factory Pattern)\n\n```csharp\npublic class OrderActor : ReceiveActor\n{\n    private readonly IDbContextFactory\u003CApplicationDbContext> _dbFactory;\n\n    public OrderActor(IDbContextFactory\u003CApplicationDbContext> dbFactory)\n    {\n        _dbFactory = dbFactory;\n\n        ReceiveAsync\u003CGetOrder>(async msg =>\n        {\n            \u002F\u002F Create fresh context for each operation\n            await using var db = await _dbFactory.CreateDbContextAsync();\n            var order = await db.Orders.FindAsync(msg.OrderId);\n            Sender.Tell(order);\n        });\n    }\n}\n\n\u002F\u002F Registration\nbuilder.Services.AddDbContextFactory\u003CApplicationDbContext>(options =>\n    options.UseNpgsql(connectionString));\n```\n\n---\n\n## Pattern 6: Query Splitting to Prevent Cartesian Explosion\n\nWhen you load multiple navigation collections via `Include()`, EF Core generates a single query that can cause cartesian explosion. If you have 10 orders with 10 items each, you get 100 rows instead of 10 + 10.\n\n### Global Configuration (Recommended for Most Cases)\n\nEnable query splitting globally in your DbContext configuration:\n\n```csharp\nservices.AddDbContext\u003CApplicationDbContext>(options =>\n    options.UseNpgsql(connectionString, npgsqlOptions =>\n        {\n            npgsqlOptions.UseQuerySplittingBehavior(QuerySplittingBehavior.SplitQuery);\n        }));\n```\n\n### Per-Query Override\n\nUse single query when you know it's more efficient:\n\n```csharp\n\u002F\u002F Use single query when you know the structure is well-understood\nvar orders = await dbContext.Orders\n    .Include(o => o.Items)\n    .Include(o => o.Payments)\n    .AsSingleQuery()  \u002F\u002F Override global split behavior\n    .ToListAsync();\n```\n\n### Trade-offs\n\n| Behavior | Pros | Cons |\n|-----------|-------|-------|\n| SplitQuery | No cartesian explosion, better for large collections | Multiple round-trips, potential consistency issues |\n| SingleQuery | Single round-trip, transactional consistency | Cartesian explosion with multiple collections |\n\n**Recommendation**: Default to `SplitQuery` globally, override with `AsSingleQuery()` for specific queries where single-query is known to be better.\n\n### When to Prefer SingleQuery\n\n- Small, well-understood navigation graphs (2-3 levels)\n- Queries where all related data is always needed\n- Performance-critical paths where round-trip cost is lower than cartesian explosion\n\n### When to Prefer SplitQuery\n\n- Large or unpredictable navigation graphs\n- Many-to-many relationships\n- Queries loading collections that may not all be needed\n\n---\n\n## Testing with EF Core\n\n### In-Memory Provider (Unit Tests Only)\n\n```csharp\n\u002F\u002F Only for simple unit tests - doesn't match real database behavior\nvar options = new DbContextOptionsBuilder\u003CApplicationDbContext>()\n    .UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString())\n    .Options;\n\nusing var context = new ApplicationDbContext(options);\n```\n\n### Real Database with TestContainers (Integration Tests)\n\nSee the `testcontainers-integration-tests` skill for proper database testing.\n\n```csharp\n\u002F\u002F Use real PostgreSQL in container\nvar container = new PostgreSqlBuilder()\n    .WithImage(\"postgres:16-alpine\")\n    .Build();\n\nawait container.StartAsync();\n\nvar options = new DbContextOptionsBuilder\u003CApplicationDbContext>()\n    .UseNpgsql(container.GetConnectionString())\n    .Options;\n```\n","# Entity Framework Core Patterns\n\n## When to Use This Skill\n\nUse this skill when:\n- Setting up EF Core in a new project\n- Optimizing query performance\n- Managing database migrations\n- Integrating EF Core with .NET Aspire\n- Debugging change tracking issues\n- Loading multiple navigation collections efficiently (query splitting)\n\n## Core Principles\n\n1. **NoTracking by Default** - Most queries are read-only; opt-in to tracking\n2. **Never Edit Migrations Manually** - Always use CLI commands\n3. **Dedicated Migration Service** - Separate migration execution from application startup\n4. **ExecutionStrategy for Retries** - Handle transient database failures\n5. **Explicit Updates** - When NoTracking, explicitly mark entities for update\n\n---\n\n## Pattern 1: NoTracking by Default\n\nConfigure your DbContext to disable change tracking by default. This improves performance for read-heavy workloads.\n\n```csharp\npublic class ApplicationDbContext : DbContext\n{\n    public ApplicationDbContext(DbContextOptions\u003CApplicationDbContext> options)\n        : base(options)\n    {\n        \u002F\u002F Disable change tracking by default for better performance on read-only queries\n        \u002F\u002F Use .AsTracking() explicitly for queries that need to track changes\n        ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;\n    }\n\n    public DbSet\u003COrder> Orders => Set\u003COrder>();\n    public DbSet\u003CCustomer> Customers => Set\u003CCustomer>();\n}\n```\n\n### When NoTracking is Active\n\n**Read-only queries work normally:**\n```csharp\n\u002F\u002F ✅ Fast read - no tracking overhead\nvar orders = await dbContext.Orders\n    .Where(o => o.Status == OrderStatus.Pending)\n    .ToListAsync();\n```\n\n**Writes require explicit handling:**\n```csharp\n\u002F\u002F ❌ WRONG - Entity not tracked, SaveChanges does nothing\nvar order = await dbContext.Orders.FirstOrDefaultAsync(o => o.Id == orderId);\norder.Status = OrderStatus.Shipped;\nawait dbContext.SaveChangesAsync(); \u002F\u002F Nothing happens!\n\n\u002F\u002F ✅ CORRECT - Explicitly mark entity for update\nvar order = await dbContext.Orders.FirstOrDefaultAsync(o => o.Id == orderId);\norder.Status = OrderStatus.Shipped;\ndbContext.Orders.Update(order); \u002F\u002F Marks entire entity as modified\nawait dbContext.SaveChangesAsync();\n\n\u002F\u002F ✅ ALSO CORRECT - Use AsTracking() for the query\nvar order = await dbContext.Orders\n    .AsTracking()\n    .FirstOrDefaultAsync(o => o.Id == orderId);\norder.Status = OrderStatus.Shipped;\nawait dbContext.SaveChangesAsync(); \u002F\u002F Works!\n```\n\n### When to Use Tracking\n\n| Scenario | Use Tracking? | Why |\n|----------|---------------|-----|\n| Display data in UI | No | Read-only, no updates |\n| API GET endpoints | No | Returning data, no mutations |\n| Update single entity | Yes or explicit Update() | Need to save changes |\n| Complex update with navigation | Yes | Tracking handles relationships |\n| Batch operations | No + ExecuteUpdate | More efficient |\n\n### Explicit Add\u002FUpdate Pattern\n\n```csharp\npublic class OrderService\n{\n    private readonly ApplicationDbContext _db;\n\n    \u002F\u002F CREATE - Always use Add (works regardless of tracking)\n    public async Task\u003COrder> CreateOrderAsync(Order order)\n    {\n        _db.Orders.Add(order);\n        await _db.SaveChangesAsync();\n        return order;\n    }\n\n    \u002F\u002F UPDATE - Explicitly mark as modified\n    public async Task UpdateOrderStatusAsync(Guid orderId, OrderStatus newStatus)\n    {\n        var order = await _db.Orders.FirstOrDefaultAsync(o => o.Id == orderId)\n            ?? throw new NotFoundException($\"Order {orderId} not found\");\n\n        order.Status = newStatus;\n        order.UpdatedAt = DateTimeOffset.UtcNow;\n\n        \u002F\u002F Explicitly mark as modified since DbContext uses NoTracking by default\n        _db.Orders.Update(order);\n        await _db.SaveChangesAsync();\n    }\n\n    \u002F\u002F DELETE - Attach and remove\n    public async Task DeleteOrderAsync(Guid orderId)\n    {\n        var order = new Order { Id = orderId };\n        _db.Orders.Remove(order);\n        await _db.SaveChangesAsync();\n    }\n}\n```\n\n---\n\n## Pattern 2: Never Edit Migrations Manually\n\n**CRITICAL:** Always use EF Core CLI commands to manage migrations. Never:\n- Manually edit migration files (except for custom SQL in `Up()`\u002F`Down()`)\n- Delete migration files directly\n- Rename migration files\n- Copy migrations between projects\n\n### Creating Migrations\n\n```bash\n# Create a new migration\ndotnet ef migrations add AddCustomerTable \\\n    --project src\u002FMyApp.Infrastructure \\\n    --startup-project src\u002FMyApp.Api\n\n# With a specific DbContext (if you have multiple)\ndotnet ef migrations add AddCustomerTable \\\n    --context ApplicationDbContext \\\n    --project src\u002FMyApp.Infrastructure \\\n    --startup-project src\u002FMyApp.Api\n```\n\n### Removing Migrations\n\n```bash\n# Remove the last migration (if not yet applied)\ndotnet ef migrations remove \\\n    --project src\u002FMyApp.Infrastructure \\\n    --startup-project src\u002FMyApp.Api\n\n# NEVER do this:\n# rm Migrations\u002F20240101_AddCustomerTable.cs  # ❌ BAD!\n```\n\n### Applying Migrations\n\n```bash\n# Apply all pending migrations\ndotnet ef database update \\\n    --project src\u002FMyApp.Infrastructure \\\n    --startup-project src\u002FMyApp.Api\n\n# Apply to a specific migration\ndotnet ef database update AddCustomerTable \\\n    --project src\u002FMyApp.Infrastructure \\\n    --startup-project src\u002FMyApp.Api\n\n# Rollback to a previous migration\ndotnet ef database update PreviousMigrationName \\\n    --project src\u002FMyApp.Infrastructure \\\n    --startup-project src\u002FMyApp.Api\n```\n\n### Generating SQL Scripts\n\n```bash\n# Generate SQL script for all migrations\ndotnet ef migrations script \\\n    --project src\u002FMyApp.Infrastructure \\\n    --startup-project src\u002FMyApp.Api \\\n    --output migrations.sql\n\n# Generate idempotent script (safe to run multiple times)\ndotnet ef migrations script \\\n    --idempotent \\\n    --project src\u002FMyApp.Infrastructure \\\n    --startup-project src\u002FMyApp.Api\n```\n\n---\n\n## Pattern 3: Dedicated Migration Service with Aspire\n\nSeparate migration execution from your main application using a dedicated migration service. This ensures:\n- Migrations complete before the app starts\n- Clean separation of concerns\n- Controlled seeding in test environments\n\n### Project Structure\n\n```\nsrc\u002F\n├── MyApp.AppHost\u002F           # Aspire orchestration\n├── MyApp.Api\u002F               # Main application\n├── MyApp.Infrastructure\u002F    # DbContext and migrations\n└── MyApp.MigrationService\u002F  # Dedicated migration runner\n```\n\n### MigrationService Program.cs\n\n```csharp\nusing MyApp.Infrastructure.Data;\nusing MyApp.MigrationService;\nusing Microsoft.EntityFrameworkCore;\n\nvar builder = Host.CreateApplicationBuilder(args);\n\n\u002F\u002F Add Aspire service defaults\nbuilder.AddServiceDefaults();\n\n\u002F\u002F Add PostgreSQL DbContext\nvar connectionString = builder.Configuration.GetConnectionString(\"appdb\")\n    ?? throw new InvalidOperationException(\"Connection string 'appdb' not found.\");\n\nbuilder.Services.AddDbContext\u003CApplicationDbContext>(options =>\n    options.UseNpgsql(connectionString, npgsqlOptions =>\n        npgsqlOptions.MigrationsAssembly(\"MyApp.Infrastructure\")));\n\n\u002F\u002F Add the migration worker\nbuilder.Services.AddHostedService\u003CMigrationWorker>();\n\nvar host = builder.Build();\nhost.Run();\n```\n\n### MigrationWorker.cs\n\n```csharp\npublic class MigrationWorker : BackgroundService\n{\n    private readonly IServiceProvider _serviceProvider;\n    private readonly IHostApplicationLifetime _hostApplicationLifetime;\n    private readonly ILogger\u003CMigrationWorker> _logger;\n\n    public MigrationWorker(\n        IServiceProvider serviceProvider,\n        IHostApplicationLifetime hostApplicationLifetime,\n        ILogger\u003CMigrationWorker> logger)\n    {\n        _serviceProvider = serviceProvider;\n        _hostApplicationLifetime = hostApplicationLifetime;\n        _logger = logger;\n    }\n\n    protected override async Task ExecuteAsync(CancellationToken stoppingToken)\n    {\n        _logger.LogInformation(\"Migration service starting...\");\n\n        try\n        {\n            using var scope = _serviceProvider.CreateScope();\n            var dbContext = scope.ServiceProvider.GetRequiredService\u003CApplicationDbContext>();\n\n            await RunMigrationsAsync(dbContext, stoppingToken);\n\n            _logger.LogInformation(\"Migration service completed successfully.\");\n        }\n        catch (Exception ex)\n        {\n            _logger.LogError(ex, \"Migration service failed: {Error}\", ex.Message);\n            throw;\n        }\n        finally\n        {\n            \u002F\u002F Stop the application after migrations complete\n            _hostApplicationLifetime.StopApplication();\n        }\n    }\n\n    private async Task RunMigrationsAsync(ApplicationDbContext dbContext, CancellationToken ct)\n    {\n        \u002F\u002F Use execution strategy for transient failure handling\n        var strategy = dbContext.Database.CreateExecutionStrategy();\n\n        await strategy.ExecuteAsync(async () =>\n        {\n            var pendingMigrations = await dbContext.Database.GetPendingMigrationsAsync(ct);\n\n            if (pendingMigrations.Any())\n            {\n                _logger.LogInformation(\"Applying {Count} pending migrations...\",\n                    pendingMigrations.Count());\n\n                await dbContext.Database.MigrateAsync(ct);\n\n                _logger.LogInformation(\"Migrations applied successfully.\");\n            }\n            else\n            {\n                _logger.LogInformation(\"No pending migrations. Database is up to date.\");\n            }\n        });\n    }\n}\n```\n\n### AppHost Configuration\n\n```csharp\nvar builder = DistributedApplication.CreateBuilder(args);\n\nvar postgres = builder.AddPostgres(\"postgres\");\nvar db = postgres.AddDatabase(\"appdb\");\n\n\u002F\u002F Migrations run first, then exit\nvar migrations = builder.AddProject\u003CProjects.MyApp_MigrationService>(\"migrations\")\n    .WaitFor(db)\n    .WithReference(db);\n\n\u002F\u002F API waits for migrations to complete\nvar api = builder.AddProject\u003CProjects.MyApp_Api>(\"api\")\n    .WaitForCompletion(migrations)  \u002F\u002F Key: waits for migrations to finish\n    .WithReference(db);\n```\n\n---\n\n## Pattern 4: ExecutionStrategy for Transient Failures\n\nAlways use `CreateExecutionStrategy()` for operations that might fail transiently:\n\n```csharp\npublic async Task UpdateWithRetryAsync(Guid id, Action\u003COrder> update)\n{\n    var strategy = _dbContext.Database.CreateExecutionStrategy();\n\n    await strategy.ExecuteAsync(async () =>\n    {\n        var order = await _dbContext.Orders\n            .AsTracking()\n            .FirstOrDefaultAsync(o => o.Id == id);\n\n        if (order is null) return;\n\n        update(order);\n        await _dbContext.SaveChangesAsync();\n    });\n}\n```\n\n**Important:** You cannot use `CreateExecutionStrategy()` with user-initiated transactions. If you need transactions with retry:\n\n```csharp\nvar strategy = _dbContext.Database.CreateExecutionStrategy();\n\nawait strategy.ExecuteAsync(async () =>\n{\n    \u002F\u002F Transaction must be INSIDE the strategy callback\n    await using var transaction = await _dbContext.Database.BeginTransactionAsync();\n\n    try\n    {\n        \u002F\u002F ... your operations ...\n        await _dbContext.SaveChangesAsync();\n        await transaction.CommitAsync();\n    }\n    catch\n    {\n        await transaction.RollbackAsync();\n        throw;\n    }\n});\n```\n\n---\n\n## Pattern 5: Bulk Operations with ExecuteUpdate\u002FExecuteDelete\n\nFor bulk operations, use EF Core 7+ `ExecuteUpdateAsync` and `ExecuteDeleteAsync` instead of loading entities:\n\n```csharp\n\u002F\u002F ❌ SLOW - Loads all entities into memory\nvar expiredOrders = await _db.Orders\n    .Where(o => o.ExpiresAt \u003C DateTimeOffset.UtcNow)\n    .ToListAsync();\n\nforeach (var order in expiredOrders)\n{\n    order.Status = OrderStatus.Expired;\n}\nawait _db.SaveChangesAsync();\n\n\u002F\u002F ✅ FAST - Single SQL UPDATE statement\nawait _db.Orders\n    .Where(o => o.ExpiresAt \u003C DateTimeOffset.UtcNow)\n    .ExecuteUpdateAsync(setters => setters\n        .SetProperty(o => o.Status, OrderStatus.Expired)\n        .SetProperty(o => o.UpdatedAt, DateTimeOffset.UtcNow));\n\n\u002F\u002F ✅ FAST - Single SQL DELETE statement\nawait _db.Orders\n    .Where(o => o.Status == OrderStatus.Cancelled && o.CreatedAt \u003C cutoffDate)\n    .ExecuteDeleteAsync();\n```\n\nThese calls execute immediately and bypass the change tracker, so check the whole write workflow:\n\n- Loaded entities keep their old values and snapshots. A later change to the same properties through\n  a tracked entity can overwrite the SQL change, even in one sequential request. Use one coherent\n  tracked save, or keep the set-based path free of tracked copies; a transaction alone does not\n  refresh tracked state.\n- Configured concurrency tokens are not checked. When optimistic concurrency is required, keep the\n  token predicate, the token update, and the affected-row check.\n- Each call executes on its own: a later `SaveChanges` neither batches it nor makes it atomic with\n  audit or outbox writes. Use one save unit, or an explicit shared transaction where atomicity is\n  required.\n- Client-side cascades and `SaveChanges`-based hooks do not run; command interceptors still see the\n  SQL. Keep the domain behavior those hooks carry instead of bypassing it to save queries.\n\n---\n\n## Pattern 6: Compiled Queries on a Hot Path\n\nOn a path that runs the *same* query shape thousands of times over a reused context, EF Core\nalready caches the translation, but it still processes the expression tree and looks up that cache on\nevery call. When the query is already minimal — an indexed lookup or a small projection — and\n`AsNoTracking` buys nothing, that per-call work is the remaining cost. `EF.CompileQuery` \u002F\n`EF.CompileAsyncQuery` compile once and reuse a delegate that bypasses the lookup; they do not make\ndatabase I\u002FO cheaper:\n\n```csharp\nprivate static readonly Func\u003CAppDbContext, int, ProductListItem> GetProduct =\n    EF.CompileQuery((AppDbContext db, int id) =>\n        db.Products.Where(p => p.Id == id)\n                   .Select(p => new ProductListItem(p.Id, p.Name, p.Price))\n                   .First());\n\npublic ProductListItem Lookup(AppDbContext db, int id) => GetProduct(db, id);\n```\n\nThe delegate is `static`, so it compiles once, and takes the `DbContext` plus each parameter as\narguments. Reach for it on endpoints or loops that execute one query shape at very high frequency; it\ndoes nothing for a one-off query, and it is the last thing to try rather than the first — a\nnon-sargable predicate or an N+1 costs far more than translation does. EF Core 9 does not support\n`EF.Parameter` or `EF.Constant` inside a compiled query.\n\n**Verify:** the hot loop's mean time drops with identical results.\n\n---\n\n## Common Pitfalls\n\n### 1. Forgetting to Update When NoTracking\n\n```csharp\n\u002F\u002F ❌ Silent failure - entity not tracked\nvar customer = await _db.Customers.FindAsync(id);\ncustomer.Name = \"New Name\";\nawait _db.SaveChangesAsync(); \u002F\u002F Does nothing!\n\n\u002F\u002F ✅ Explicit update\nvar customer = await _db.Customers.FindAsync(id);\ncustomer.Name = \"New Name\";\n_db.Customers.Update(customer);\nawait _db.SaveChangesAsync();\n```\n\n### 2. N+1 Query Problem\n\n```csharp\n\u002F\u002F ❌ N+1 queries - one query per order\nvar customers = await _db.Customers.ToListAsync();\nforeach (var customer in customers)\n{\n    var orders = customer.Orders; \u002F\u002F Lazy load triggers query\n}\n\n\u002F\u002F ✅ Eager loading - single query\nvar customers = await _db.Customers\n    .Include(c => c.Orders)\n    .ToListAsync();\n```\n\n### 3. Tracking Conflicts with Multiple DbContext Instances\n\n```csharp\n\u002F\u002F ❌ Tracking conflict - entity tracked by different context\nvar order1 = await _db1.Orders.AsTracking().FindAsync(id);\nvar order2 = await _db2.Orders.AsTracking().FindAsync(id);\norder2.Status = OrderStatus.Shipped;\nawait _db2.SaveChangesAsync(); \u002F\u002F May throw or behave unexpectedly\n\n\u002F\u002F ✅ Use single context or detach first\n_db1.Entry(order1).State = EntityState.Detached;\n```\n\n### 4. Not Using Async Consistently\n\n```csharp\n\u002F\u002F ❌ Blocking call in async context\nvar orders = _db.Orders.ToList(); \u002F\u002F Blocks thread\n\n\u002F\u002F ✅ Async all the way\nvar orders = await _db.Orders.ToListAsync();\n```\n\n### 5. Querying Inside Loops\n\n```csharp\n\u002F\u002F ❌ Query per iteration\nforeach (var orderId in orderIds)\n{\n    var order = await _db.Orders.FindAsync(orderId);\n    \u002F\u002F process order\n}\n\n\u002F\u002F ✅ Single query\nvar orders = await _db.Orders\n    .Where(o => orderIds.Contains(o.Id))\n    .ToListAsync();\n```\n\n---\n\n## DbContext Lifetime in DI\n\n### ASP.NET Core (Scoped by Default)\n\n```csharp\n\u002F\u002F Scoped = one instance per HTTP request\nbuilder.Services.AddDbContext\u003CApplicationDbContext>(options =>\n    options.UseNpgsql(connectionString));\n```\n\n### Background Services (Create Scope)\n\n```csharp\npublic class MyBackgroundService : BackgroundService\n{\n    private readonly IServiceProvider _serviceProvider;\n\n    protected override async Task ExecuteAsync(CancellationToken stoppingToken)\n    {\n        \u002F\u002F ✅ Create scope for each unit of work\n        using var scope = _serviceProvider.CreateScope();\n        var dbContext = scope.ServiceProvider.GetRequiredService\u003CApplicationDbContext>();\n\n        \u002F\u002F ... use dbContext ...\n    }\n}\n```\n\n### Actors \u002F Long-Lived Objects (Factory Pattern)\n\n```csharp\npublic class OrderActor : ReceiveActor\n{\n    private readonly IDbContextFactory\u003CApplicationDbContext> _dbFactory;\n\n    public OrderActor(IDbContextFactory\u003CApplicationDbContext> dbFactory)\n    {\n        _dbFactory = dbFactory;\n\n        ReceiveAsync\u003CGetOrder>(async msg =>\n        {\n            \u002F\u002F Create fresh context for each operation\n            await using var db = await _dbFactory.CreateDbContextAsync();\n            var order = await db.Orders.FindAsync(msg.OrderId);\n            Sender.Tell(order);\n        });\n    }\n}\n\n\u002F\u002F Registration\nbuilder.Services.AddDbContextFactory\u003CApplicationDbContext>(options =>\n    options.UseNpgsql(connectionString));\n```\n\n---\n\n## Pattern 6: Query Splitting to Prevent Cartesian Explosion\n\nWhen you load multiple navigation collections via `Include()`, EF Core generates a single query that can cause cartesian explosion. If you have 10 orders with 10 items each, you get 100 rows instead of 10 + 10.\n\n### Global Configuration (Recommended for Most Cases)\n\nEnable query splitting globally in your DbContext configuration:\n\n```csharp\nservices.AddDbContext\u003CApplicationDbContext>(options =>\n    options.UseNpgsql(connectionString, npgsqlOptions =>\n        {\n            npgsqlOptions.UseQuerySplittingBehavior(QuerySplittingBehavior.SplitQuery);\n        }));\n```\n\n### Per-Query Override\n\nUse single query when you know it's more efficient:\n\n```csharp\n\u002F\u002F Use single query when you know the structure is well-understood\nvar orders = await dbContext.Orders\n    .Include(o => o.Items)\n    .Include(o => o.Payments)\n    .AsSingleQuery()  \u002F\u002F Override global split behavior\n    .ToListAsync();\n```\n\n### Trade-offs\n\n| Behavior | Pros | Cons |\n|-----------|-------|-------|\n| SplitQuery | No cartesian explosion, better for large collections | Multiple round-trips, potential consistency issues |\n| SingleQuery | Single round-trip, transactional consistency | Cartesian explosion with multiple collections |\n\n**Recommendation**: Default to `SplitQuery` globally, override with `AsSingleQuery()` for specific queries where single-query is known to be better.\n\n### When to Prefer SingleQuery\n\n- Small, well-understood navigation graphs (2-3 levels)\n- Queries where all related data is always needed\n- Performance-critical paths where round-trip cost is lower than cartesian explosion\n\n### When to Prefer SplitQuery\n\n- Large or unpredictable navigation graphs\n- Many-to-many relationships\n- Queries loading collections that may not all be needed\n\n---\n\n## Testing with EF Core\n\n### In-Memory Provider (Unit Tests Only)\n\n```csharp\n\u002F\u002F Only for simple unit tests - doesn't match real database behavior\nvar options = new DbContextOptionsBuilder\u003CApplicationDbContext>()\n    .UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString())\n    .Options;\n\nusing var context = new ApplicationDbContext(options);\n```\n\n### Real Database with TestContainers (Integration Tests)\n\nSee the `testcontainers-integration-tests` skill for proper database testing.\n\n```csharp\n\u002F\u002F Use real PostgreSQL in container\nvar container = new PostgreSqlBuilder()\n    .WithImage(\"postgres:16-alpine\")\n    .Build();\n\nawait container.StartAsync();\n\nvar options = new DbContextOptionsBuilder\u003CApplicationDbContext>()\n    .UseNpgsql(container.GetConnectionString())\n    .Options;\n```\n",{"name":5,"description":7},"master","b30b1c1908dbc56a8184128f18803053d762ccb5","opencode\u002Fdeniz-dotnet-general\u002Fskills\u002Fdeniz-dotnet-general.efcore-patterns",0,"https:\u002F\u002Fgithub.com\u002FBlind-Striker\u002Fagent-skills-and-plugins","https:\u002F\u002Fgithub.com\u002FBlind-Striker","denizirgin.com","VP of Engineering - \r\n@armutcom @homeruntech @prontopro\r\n |  Speaker \r\n@CodeFiction\r\n, http:\u002F\u002Fcodefiction.tech | Developer, gamer, blogger, maiden iron fan","2026-11-13 00:23:18",{"source":8,"skillName":5,"commands":34,"prompt":44,"zipAvailable":45},[35,38,41],{"tool":36,"command":37},"npx","npx skills add Blind-Striker\u002Fagent-skills-and-plugins --skill deniz-dotnet-general.efcore-patterns",{"tool":39,"command":40},"bunx","bunx skills add Blind-Striker\u002Fagent-skills-and-plugins --skill deniz-dotnet-general.efcore-patterns",{"tool":42,"command":43},"pnpm","pnpm dlx skills add Blind-Striker\u002Fagent-skills-and-plugins --skill deniz-dotnet-general.efcore-patterns","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FBlind-Striker\u002Fagent-skills-and-plugins\u002Fblob\u002Fmaster\u002Fopencode\u002Fdeniz-dotnet-general\u002Fskills\u002Fdeniz-dotnet-general.efcore-patterns\u002FSKILL.md",true,[],[48,55,62,69,76,83],{"skillNo":49,"name":50,"nameZh":6,"description":51,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":52,"categories":53,"keywords":54,"publishedAt":19},"01M79YGWBJ52PHMSTKJ3RJ3AWR","writing-tunit-tests","Write tests in TUnit — the attributes, the async assertion model, data-driven cases, lifecycle hooks, and the parallelism rules. USE FOR writing or fixing a test in a TUnit project, translating a test idea into TUnit syntax, or reviewing TUnit test code for API mistakes. DO NOT USE FOR deciding what to test, judging whether a test is any good, or running tests.","https:\u002F\u002Fgithub.com\u002FBlind-Striker\u002Fagent-skills-and-plugins\u002Fblob\u002Fmaster\u002Fskills\u002Fdeniz-dotnet-general\u002Fwriting-tunit-tests\u002FSKILL.md",[],[],{"skillNo":56,"name":57,"nameZh":6,"description":58,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":59,"categories":60,"keywords":61,"publishedAt":19},"01M79YGR3Y9RCRS6TD71D0KKP8","dotnet-walls","Walls for a .NET change in a repository without its own quality gates — pinned, ephemeral analyzer, format, clone and scanner commands for the verify step, their identity ratchet, and the build traps. Use during a walls preflight, or when a worker's verify step needs .NET quality gates.","https:\u002F\u002Fgithub.com\u002FBlind-Striker\u002Fagent-skills-and-plugins\u002Fblob\u002Fmaster\u002Fskills\u002Fdeniz-dotnet-general\u002Fdotnet-walls\u002FSKILL.md",[],[],{"skillNo":63,"name":64,"nameZh":6,"description":65,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":66,"categories":67,"keywords":68,"publishedAt":19},"01M79YGFNJBST7D803NQW3SBYM","csharp-15","Write, review and modernize C# 15 (.NET 11) code correctly. Covers every C# 15 feature - collection expression arguments (`[with(...), ...]`), union types (`union`, `[Union]`, `IUnion`, custom unions), closed class hierarchies (`closed`), extension indexers, labeled `break`\u002F`continue`, non-virtual static interface members on runtimes without default interface methods, and the preview memory-safety model (`unsafe(expr)`, `safe`, requires-unsafe members). Use when code targets net11.0 or LangVersion 15\u002Fpreview, when the user mentions any of these features, when replacing marker interfaces, OneOf-style results, `goto`\u002Fflag loop exits or capacity\u002Fcomparer boilerplate, or when the build reports CS8121, CS8509, CS8655, CS8510, CS0121\u002FCS0411 on a `with(...)` element, CS9370, CS9380 or CS9363.","https:\u002F\u002Fgithub.com\u002FBlind-Striker\u002Fagent-skills-and-plugins\u002Fblob\u002Fmaster\u002Fskills\u002Fdeniz-dotnet-general\u002Fcsharp-15\u002FSKILL.md",[],[],{"skillNo":70,"name":71,"nameZh":6,"description":72,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":73,"categories":74,"keywords":75,"publishedAt":19},"01M79YGAV031473HSX6FN87ENH","verified-waves","Run one task as verified multi-agent waves. Plans the fan-out, sends findings to fresh skeptics, keeps a ledger, and reports N of M done; small tasks stay solo.","https:\u002F\u002Fgithub.com\u002FBlind-Striker\u002Fagent-skills-and-plugins\u002Fblob\u002Fmaster\u002Fskills\u002Fdeniz-coordination\u002Fverified-waves\u002FSKILL.md",[],[],{"skillNo":77,"name":78,"nameZh":6,"description":79,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":80,"categories":81,"keywords":82,"publishedAt":19},"01M79YG6QXNND4WRPP3GATSY8J","harness","The bundled dispatch harness, which runs a task file on worker models through OpenCode or Codex, fences their writes, escalates their asks to the operator, settles each result from git and its verify commands, and records every step in a ledger. Its commands, task file, modes and write fence, configuration, runs and their recovery, ledger and exit codes.","https:\u002F\u002Fgithub.com\u002FBlind-Striker\u002Fagent-skills-and-plugins\u002Fblob\u002Fmaster\u002Fskills\u002Fdeniz-coordination\u002Fharness\u002FSKILL.md",[],[],{"skillNo":84,"name":85,"nameZh":6,"description":86,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":87,"categories":88,"keywords":89,"publishedAt":19},"01M79YG2P5S91SDTA5912XJ4FV","delegating-to-worker-models","Use when you hand off implementation, a plan, research a decision will rely on, or a review, and you brief the worker and check what comes back. A subagent that searches, reads in parallel, or keeps your context small is ordinary tool use. Covers what stays with you, the mechanism, assigning work by strength, the walls preflight, prompts without contradictions, the worker contract and model profiles, evidence from your own run, review, and the fix-up loop.","https:\u002F\u002Fgithub.com\u002FBlind-Striker\u002Fagent-skills-and-plugins\u002Fblob\u002Fmaster\u002Fskills\u002Fdeniz-coordination\u002Fdelegating-to-worker-models\u002FSKILL.md",[],[]]