.NET 9 / 10 ASP.NET Core Entity Framework Core Blazor xUnit

Claude Code for C# Developers

Complete guide for .NET developers: ASP.NET Core, Entity Framework, Blazor, nullable types, LINQ, pattern matching, and 40+ copy-paste prompts.

Why C# Developers Choose Claude Code

🏗️

Full .NET stack awareness

Understands ASP.NET Core, EF Core, Blazor, MAUI, Orleans, Aspire — and which version you're on.

🔒

Nullable & type safe

Generates null-safe code by default. Enables nullable reference types, uses records, avoids NRE landmines.

Modern C# idioms

Uses records, primary constructors, required members, collection expressions, and switch expressions correctly.

🧪

xUnit / NUnit / Moq

Generates complete test suites with mocks, FluentAssertions, and theory-based parameterised tests.

Project Setup for Maximum Productivity

Tell Claude Code your .NET version, framework, and architecture upfront. A good CLAUDE.md eliminates repeated context.

CLAUDE.md for .NET Projects

.NET Create a CLAUDE.md for a .NET 9 ASP.NET Core Web API project using EF Core with PostgreSQL, the Clean Architecture pattern (Domain/Application/Infrastructure/Api layers), and xUnit + NSubstitute for testing. Include conventions for nullable reference types, record types for DTOs, and our logging approach with ILogger<T>.
.NET Scaffold a new .NET 9 solution with three projects: MyApp.Domain (class library), MyApp.Application (class library), MyApp.Api (ASP.NET Core Web API). Wire up dependency injection, add a health check endpoint, configure Serilog for structured logging, and set up nullable reference types in all .csproj files.
.NET Add a global.json pinning the .NET 9 SDK version, a .editorconfig enforcing our C# code style (tabs=4 spaces, braces on new line, prefer var for obvious types), and a Directory.Build.props that enables nullable, implicit usings, and treats warnings as errors across all projects in the solution.

NuGet & Dependency Management

NuGet Audit all NuGet packages in the solution for outdated versions and known vulnerabilities using dotnet list package --outdated and dotnet list package --vulnerable. Suggest safe upgrade paths and flag any packages with breaking changes between current and latest versions.
NuGet Add a Directory.Packages.props file to centralise all NuGet package versions across the solution using Central Package Management. Move all version attributes from individual .csproj files to this file, keeping package references in projects without version attributes.

ASP.NET Core Web API

Claude Code generates production-quality controllers, minimal APIs, middleware, and OpenAPI specs that follow ASP.NET Core conventions.

Controllers & Endpoints

ASP.NET Add a ProductsController with CRUD endpoints (GET list with pagination, GET by id, POST create, PUT update, DELETE). Use [ApiController] and [Route("api/[controller]")], inject IProductService, return ProblemDetails on errors, and produce a 201 Created with Location header on POST.
ASP.NET Refactor these controllers to use Minimal API syntax (MapGet, MapPost etc.) in a ProductEndpoints class with static extension methods on IEndpointRouteBuilder. Preserve all OpenAPI metadata using .WithName(), .WithTags(), .Produces<T>(), and .WithOpenApi().
Validation Add FluentValidation for the CreateOrderRequest and UpdateOrderRequest DTOs. Wire up the validators as scoped services, enable automatic validation via AddFluentValidationAutoValidation(), and ensure validation errors return a 400 ProblemDetails response with field-level error messages.
Auth Add JWT Bearer authentication to Program.cs with refresh token support. Create an AuthController with /login and /refresh endpoints, use IConfiguration to read the JWT secret from appsettings, and protect all other controllers with [Authorize]. Include the correct lifetime for the auth middleware in the pipeline.
Middleware Write a global exception handling middleware that catches all unhandled exceptions, logs them with ILogger including the request path and correlation ID, and returns a ProblemDetails response with appropriate HTTP status codes (404 for NotFoundException, 409 for ConflictException, 500 for everything else).
OpenAPI Configure Scalar (or Swagger UI) for this Web API using Microsoft.AspNetCore.OpenApi. Add XML comments to all public DTOs and controllers, configure JWT authentication in the OpenAPI spec, and ensure all endpoints have summary, description, and response type annotations.

Background Services & Queuing

Worker Create a BackgroundService that processes items from a Channel<T> queue. Expose an IOrderProcessingQueue interface to enqueue work from controllers, process items with a configurable concurrency limit using SemaphoreSlim, and handle cancellation via CancellationToken on application shutdown.
Resilience Add Microsoft.Extensions.Http.Resilience (Polly v8) to all HttpClient registrations. Configure a retry policy with exponential backoff, a circuit breaker that opens after 5 failures, and a timeout of 10 seconds per request. Log each retry and circuit break event.

Entity Framework Core

Claude Code reads your DbContext and entity models to generate type-safe queries, migrations, and bulk operations without N+1 problems.
EF Core Write a LINQ query that fetches all orders for a customer within a date range, includes the line items and their product names, paginates using Skip/Take, and returns an OrderSummaryDto using a projection (Select) — avoiding the N+1 problem and unnecessary columns.
EF Core Add a migration that renames the column Users.FullName to Users.DisplayName, adds a non-nullable Email column with a unique index, and backfills Email from a separate UserEmails table. Make the migration reversible with a correct Down() method.
EF Core Replace these row-by-row update loops with EF Core 7+ ExecuteUpdateAsync and ExecuteDeleteAsync bulk operations. Preserve the domain logic and add a check that affected row counts match expectations, throwing if not to catch partial failures.
EF Core Configure value objects in EF Core using Owned Entities for Address (Street, City, PostCode) embedded in the Orders table. Add proper null handling for optional owned entities and configure column naming conventions so Address_ is not prefixed on column names.
EF Core Add a generic repository pattern with IRepository<T> and specification pattern (ISpecification<T>) so queries can be composed and reused. Include an EvaluateAsync method that applies Where, Include, OrderBy, Skip, Take from the specification, and returns paginated results as a PagedResult<T>.
Performance Profile this DbContext using .EnableSensitiveDataLogging() and .EnableDetailedErrors() in development, then identify all queries missing AsNoTracking() for read-only paths. Add compiled queries using EF.CompileAsyncQuery for the three most frequently called hot paths.

Modern C# Language Features

Claude Code uses records, pattern matching, primary constructors, required properties, and collection expressions — the right feature for each scenario.

Records & Immutable Types

Records Refactor these DTO classes to positional records, add a domain model layer using record classes with init-only properties and value semantics, and use with-expressions for update operations. Ensure JSON serialization with System.Text.Json works correctly — including the [JsonPropertyName] attributes where needed.
Records Create a Result<T, TError> discriminated union using records (Ok and Err subtypes) and implement railway-oriented programming for the order processing pipeline. Chain operations with Map, Bind, and Match methods, and avoid throwing exceptions for expected business failures.

Pattern Matching & Switch Expressions

Pattern Rewrite this if-else chain that branches on the type of a notification (Email, SMS, Push, Webhook) into a switch expression using type patterns and property patterns. Extract the logic to a Dispatch method on the notification handler that is exhaustive — compiler should warn on unhandled cases.
Pattern Implement a state machine for an Order (Pending → Confirmed → Shipped → Delivered | Cancelled) using a readonly record struct for state and a switch expression for the Transition(OrderEvent) method. Make invalid transitions throw a descriptive DomainException with the current state and attempted event.

Async/Await & Concurrency

Async Refactor these sequential async calls to run in parallel using Task.WhenAll. Handle partial failures so one failed task doesn't cancel the others — collect all results and errors, return a summary. Add ConfigureAwait(false) on all awaits in library code.
Async Convert this IEnumerable pipeline that processes batches of records to use IAsyncEnumerable<T> with await foreach. The producer reads pages from the database using EF Core and the consumer applies transformations — use a Channel<T> to decouple them and avoid loading all records into memory.
Concurrency Add a distributed lock using Redis (StackExchange.Redis) or a database advisory lock for the nightly batch job so it only runs on one instance in a multi-pod deployment. Implement an IDistributedLock abstraction so tests can use a fake in-memory implementation.

Dependency Injection & Configuration

DI Implement the Options pattern for all configuration sections (DatabaseOptions, EmailOptions, FeatureFlags). Use IOptions<T> for singleton config, IOptionsSnapshot<T> for per-request config that reloads on change, and IOptionsMonitor<T> for background services. Add data annotation validation on each options class.
DI Register all services in this Application and Infrastructure layer using convention-based scanning with Scrutor — scan for all classes implementing IRepository<>, IService, or ICommandHandler and register them with the correct lifetime. Avoid manual one-by-one registrations in Program.cs.

Blazor (WebAssembly & Server)

Claude Code understands Blazor's component lifecycle, render modes, state management, and JavaScript interop across both Server and WASM hosting.
Blazor Build a Blazor data table component that accepts an IQueryable<T> source, supports column sorting (click header), filtering (search box), and server-side pagination. Expose it as a generic component <DataTable TItem="Order"> with a ColumnDefinition parameter using RenderFragment<T>.
Blazor Add a cascading authentication state to this Blazor app. Create an AppState service using CascadingValue, inject it into child components, and add role-based rendering so admin-only UI sections are hidden from regular users. Use [CascadingParameter] correctly in child components.
Interop Write a Blazor JavaScript interop wrapper for the Clipboard API. Create a ClipboardService with CopyToClipboardAsync(string text) using IJSRuntime.InvokeVoidAsync, handle the NotSupportedException when the browser denies clipboard access, and add a fallback using execCommand for older browsers via a JS module.
Blazor Implement optimistic UI updates in this Blazor form component: when the user submits, immediately update the local state and call StateHasChanged, then await the API call and roll back on failure with an error message. Use a loading spinner on the button during the async operation.

Testing C# with xUnit, NUnit & Mocking

Claude Code generates complete test classes with arrange-act-assert structure, meaningful names, and the right mocking framework for your stack.
xUnit Write xUnit tests for the OrderService class. Use NSubstitute to mock IOrderRepository and IEmailService. Cover: successful order creation, repository throws NotFoundException, email service fails (should not fail the order), and the concurrent duplicate order scenario. Use FluentAssertions for all assertions.
xUnit Add [Theory] tests with [InlineData] and [MemberData] for the discount calculation logic — cover all boundary conditions (0%, edge of tier, 100%). Add a [ClassData] source that reads edge cases from a JSON file so non-developers can maintain the test data without touching C# code.
Integration Set up a WebApplicationFactory integration test for the ProductsController using Testcontainers for .NET to spin up a real PostgreSQL container. Seed test data in a shared fixture, use IClassFixture for container lifetime, and add a helper that resets the database between test classes.
Test Add mutation testing to this project using Stryker.NET. Configure stryker-config.json to target the Application layer, exclude the generated migration files, and set a minimum mutation score threshold of 80%. Explain the top 3 surviving mutants and how to add tests that kill them.
Benchmark Add a BenchmarkDotNet benchmark for the three hottest code paths identified by profiling: the LINQ aggregation query, the JSON serialisation of large response objects, and the password hashing. Run with [MemoryDiagnoser] and [ThreadingDiagnoser], then suggest the fastest alternative implementation for each.

LINQ & Functional Patterns

LINQ Rewrite this nested foreach report-builder into LINQ method syntax. Use GroupBy for the category aggregation, SelectMany to flatten nested collections, and OrderByDescending + ThenBy for the multi-key sort. Ensure no ToList() mid-query causes multiple database round-trips.
LINQ Add LINQ 6 (or MoreLINQ) operators to this project: use Chunk to batch items for bulk API calls, DistinctBy on a key selector instead of Select-GroupBy-Select, and MinBy/MaxBy for finding extreme values without sorting. Show the before/after for each.
Functional Implement a pipeline of transformation steps (validate → enrich → transform → persist) using function composition with Func<T, T> delegates and a Pipe extension method. Each step should be independently testable and the full pipeline should short-circuit on first failure using a Result<T> monad.

Tooling, Docker & CI/CD

Docker Write a multi-stage Dockerfile for this ASP.NET Core app: stage 1 restores NuGet packages, stage 2 builds and publishes in Release mode, stage 3 is the runtime image using mcr.microsoft.com/dotnet/aspnet:9.0. Use a non-root user for the runtime stage and add a HEALTHCHECK instruction.
CI Create a GitHub Actions workflow that builds the .NET solution, runs xUnit tests with code coverage using Coverlet (fail below 80%), publishes the test report as a PR comment using dorny/test-reporter, and builds + pushes the Docker image to GitHub Container Registry on merge to main.
Roslyn Add a Roslyn analyzer (source generator) that checks all public API methods return Task or Task<T> for async methods. Generate a diagnostic warning with a code fix that adds the Async suffix to any async method missing it. Write a unit test for the analyzer using Microsoft.CodeAnalysis.Testing.
MAUI Set up a .NET MAUI project targeting Android and iOS with a shared ViewModel using CommunityToolkit.Mvvm [ObservableProperty] and [RelayCommand]. Add platform-specific implementations of an IPermissionsService for camera access using DependencyService or the MAUI DI container.

All 40+ Prompts at a Glance

How to use these prompts

Paste any prompt directly into Claude Code (CLI: claude). Prefix with your context — e.g. "Given my ProductsController at src/Api/Controllers/ProductsController.cs, …" — for best results. Claude Code reads the file automatically if you mention the path.

CategoryPrompt summary
.NET SetupCLAUDE.md for Clean Architecture .NET 9
.NET SetupScaffold 3-project solution with DI + Serilog
.NET Setupglobal.json + .editorconfig + Directory.Build.props
NuGetAudit outdated + vulnerable packages
NuGetCentral Package Management migration
ASP.NET CoreCRUD controller with ProblemDetails
ASP.NET CoreMigrate controllers to Minimal APIs
ASP.NET CoreFluentValidation + 400 ProblemDetails
ASP.NET CoreJWT auth + refresh token controller
ASP.NET CoreGlobal exception handling middleware
ASP.NET CoreScalar/Swagger OpenAPI with XML docs
ASP.NET CoreChannel<T> background worker with concurrency
ASP.NET CorePolly v8 resilience pipeline for HttpClient
EF CorePaginated query with projection (no N+1)
EF CoreSafe schema migration with backfill
EF CoreBulk update/delete with ExecuteUpdateAsync
EF CoreOwned Entity value objects (Address)
EF CoreGeneric repository + specification pattern
EF CoreAsNoTracking audit + compiled queries
RecordsDTO refactor to positional records
RecordsResult<T,E> discriminated union railway
Pattern matchingSwitch expression for notification dispatch
Pattern matchingState machine with exhaustive switch
AsyncSequential → parallel Task.WhenAll with error handling
AsyncIAsyncEnumerable + Channel producer/consumer
AsyncDistributed lock for singleton batch job
DIIOptions/IOptionsSnapshot/IOptionsMonitor pattern
DIConvention-based service scanning with Scrutor
BlazorGeneric DataTable component with sort/filter/page
BlazorCascading auth state + role-based rendering
BlazorClipboard API JavaScript interop wrapper
BlazorOptimistic UI updates with rollback
xUnitNSubstitute mocks + FluentAssertions full suite
xUnitTheory tests with MemberData + JSON fixture file
IntegrationWebApplicationFactory + Testcontainers PostgreSQL
MutationStryker.NET mutation testing setup
BenchmarkBenchmarkDotNet for hot paths
LINQNested foreach → LINQ method chain
LINQChunk/DistinctBy/MinBy/MaxBy operators
FunctionalPipe composition with Result monad
DockerMulti-stage Dockerfile with non-root user
CI/CDGitHub Actions: build, test coverage, Docker push
RoslynAnalyzer + code fix for Async suffix
MAUICommunityToolkit.Mvvm + platform permissions

Frequently Asked Questions

Does Claude Code understand C# nullable reference types and null safety?
Yes — Claude Code fully understands C#'s nullable reference type system (enabled via <Nullable>enable</Nullable> in .csproj). It correctly distinguishes between string (non-nullable) and string? (nullable), uses the null-forgiving operator ! only when justified, and avoids null reference exceptions by using null-conditional operators (?.), null-coalescing (?? and ??=), and pattern matching (if (x is not null)). When auditing existing code, Claude identifies nullable annotation mismatches and adds the correct [NotNull], [MaybeNull] attributes. Prompt: "Enable nullable reference types across this project and fix all warnings — explain every case where you use ! and why it is safe."
How does Claude Code work with ASP.NET Core Web API?
Claude Code understands the full ASP.NET Core pipeline: minimal APIs, controllers, middleware, filters, dependency injection, IOptions<T> configuration, and ILogger<T>. It generates controllers with correct [ApiController], [Route], [HttpGet/Post/Put/Delete] attributes, produces OpenAPI-compatible responses, and wires up services in Program.cs. It understands the difference between scoped, transient, and singleton lifetimes and chooses the right one. Prompt: "Add a POST /api/orders endpoint with FluentValidation, a service interface injected via constructor, and a 201 Created response with the Location header set to the new resource URL."
How does Claude Code handle Entity Framework Core?
Claude Code reads your DbContext, entity models, and existing migrations to generate compatible EF Core queries and new migrations. It writes LINQ-to-SQL expressions that translate correctly (avoiding client-side evaluation traps), uses Include/ThenInclude for eager loading, AsNoTracking for read-only queries, and ExecuteUpdateAsync/ExecuteDeleteAsync for bulk operations in EF Core 7+. For migrations, it generates Up/Down methods correctly and flags destructive schema changes. Prompt: "Add a query that fetches orders with their line items and product names, filters by customer and date range, paginates using Skip/Take, and returns a lightweight DTO — avoiding the N+1 problem."
Does Claude Code understand C# records, pattern matching, and modern language features?
Yes. Claude Code uses C# records correctly — positional records for immutable DTOs, record classes with init-only properties and value semantics, and with-expressions for non-destructive mutation. For pattern matching, it writes switch expressions with type patterns, property patterns, positional patterns, and guards. It uses required properties (C# 11), primary constructors (C# 12), collection expressions (C# 12), and ref readonly parameters appropriately. Prompt: "Refactor these DTOs to use records, add a domain model that uses a discriminated union-style hierarchy with pattern matching for processing, and keep the JSON serialization working."
How does Claude Code work with Blazor (WebAssembly and Server)?
Claude Code understands both Blazor Server (SignalR-based) and Blazor WebAssembly, including the .NET 8+ Auto render mode. It correctly places [Parameter], [CascadingParameter], [Inject] attributes, writes EventCallback<T> for child-to-parent communication, uses IJSRuntime for JavaScript interop, and scopes state management with services. It avoids common mistakes like calling StateHasChanged without await and mutating parameters from child components. Prompt: "Build a Blazor component that fetches paginated data from an API, shows a loading skeleton, handles errors with a retry button, and deep-links the current page via the URL."
How does Claude Code help with unit testing in C# (xUnit, NUnit, Moq, NSubstitute)?
Claude Code generates xUnit tests with [Fact] and [Theory] + [InlineData]/[MemberData], NUnit tests with [Test] and [TestCase], and MSTest when required. For mocking, it writes Moq setups with Setup/Returns/Verify and NSubstitute equivalents. It correctly uses AutoFixture for test data, FluentAssertions for readable assertions, and arranges async tests with async Task and await. Prompt: "Write xUnit tests for this service class using NSubstitute for its two dependencies, cover the happy path, null input, and the case where the repository throws — use FluentAssertions."
Does Claude Code understand LINQ and functional data transformation in C#?
Claude Code writes idiomatic LINQ — both query syntax and method syntax — correctly. It chooses the right operators: SelectMany for flattening, GroupBy for aggregations, Zip for pairing sequences, Chunk for batching (.NET 6+), and DistinctBy/MinBy/MaxBy (.NET 6+). It avoids ToList() materialisation mid-query unless necessary, uses lazy evaluation correctly, and knows when PLINQ (AsParallel()) is appropriate. Prompt: "Rewrite this nested foreach that builds a grouped report into LINQ — preserve the null-safety, avoid multiple enumeration, and add a benchmark comment showing the O(n) improvement."

Related Resources

⚡ Using Claude Code? 30 power prompts that 2× your output · £5 £3 first 10Get PDF £3 →