# .NET & Visual Studio .NET & Visual Studio

Level-500-Referenz zu .NET 8/9, C#, ASP.NET Core, EF Core, Visual Studio, VS Code, NuGet, Tests, Containerisierung, GitHub Actions und Azure SDKs. Level 500 reference for .NET 8/9, C#, ASP.NET Core, EF Core, Visual Studio, VS Code, NuGet, testing, containerization, GitHub Actions, and Azure SDKs.

.NET 8/9 .NET 8/9
LTS und aktuelle Runtime LTS and current runtime
C# 12+ C# 12+
Records, patterns, primary ctors Records, patterns, primary ctors
ASP.NET Core ASP.NET Core
Web APIs, Blazor, gRPC, SignalR Web APIs, Blazor, gRPC, SignalR
CI/CD CI/CD
GitHub Actions und Azure DevOps GitHub Actions and Azure DevOps
💡 Moderne .NET-Entwicklung ist Plattform-, Paket- und Pipeline-Engineering 💡 Modern .NET development is platform, package, and pipeline engineering

Die produktive Qualität eines .NET-Stacks entsteht aus SDK-Management, C#-Sprachfeatures, Hosting-Modell, Observability, NuGet-Strategie, Testpyramide und reproduzierbarer CI/CD-Pipeline. The production quality of a .NET stack comes from SDK management, C# language features, hosting model, observability, NuGet strategy, test pyramid, and a reproducible CI/CD pipeline.

CLI und Templates CLI and templates

dotnet new/build/run/test/publish dotnet new/build/run/test/publish

C# Sprache C# language

Nullable, records, patterns, LINQ Nullable, records, patterns, LINQ

ASP.NET Core ASP.NET Core

Minimal APIs, Blazor, auth, DI Minimal APIs, Blazor, auth, DI

EF Core EF Core

Migrations, change tracking, performance Migrations, change tracking, performance

Tooling und Delivery Tooling and delivery

Visual Studio, VS Code, NuGet, tests, containers Visual Studio, VS Code, NuGet, tests, containers

## .NET SDK, Runtime, CLI und Projektvorlagen .NET SDK, runtime, CLI, and project templates

Befehl / Konzept Command / concept | Wofür What for | Beispiel Example | Hinweis Note
--- | --- | --- | ---
dotnet --info dotnet --info | SDKs, Runtimes und Hostinformationen prüfen Check SDKs, runtimes, and host info | dotnet --info dotnet --info | Basisdiagnose bei Build- oder Runtime-Problemen Baseline diagnostics for build or runtime problems
dotnet new dotnet new | Projekt- oder Lösungsgerüst erzeugen Create project or solution scaffolding | dotnet new webapi -n Api dotnet new webapi -n Api | Template-Optionen mit --help prüfen Review template options with --help
dotnet restore dotnet restore | NuGet-Abhängigkeiten auflösen Resolve NuGet dependencies | dotnet restore dotnet restore | Private feeds und lock files berücksichtigen Account for private feeds and lock files
dotnet build dotnet build | Kompiliert den Code Compiles the code | dotnet build -c Release dotnet build -c Release | Deterministische Builds in CI erzwingen Enforce deterministic builds in CI
dotnet run dotnet run | Startet die Anwendung lokal Runs the application locally | dotnet run --project src/App dotnet run --project src/App | Nur für Dev-Loop, nicht für Production Hosting For dev loop only, not production hosting
dotnet test dotnet test | Führt Unit- und Integrationstests aus Runs unit and integration tests | dotnet test --collect:"XPlat Code Coverage" dotnet test --collect:"XPlat Code Coverage" | Flaky Tests im Pipeline-Design beachten Account for flaky tests in pipeline design
dotnet publish dotnet publish | Erzeugt deploybare Artefakte Produces deployable artifacts | dotnet publish -c Release -r win-x64 --self-contained false dotnet publish -c Release -r win-x64 --self-contained false | RID, trimming und AOT bewusst wählen Choose RID, trimming, and AOT deliberately
global.json global.json | Pinnt die SDK-Version Pins the SDK version | {"sdk":{"version":"8.0.204"}} {"sdk":{"version":"8.0.204"}} | Verhindert unbeabsichtigte SDK-Drifts Prevents accidental SDK drift

CLI CLI

    dotnet new sln -n Contoso.Platform
    dotnet new webapi -n Contoso.Api
    dotnet new xunit -n Contoso.Api.Tests
    dotnet sln add .\Contoso.Api\Contoso.Api.csproj
    dotnet sln add .\Contoso.Api.Tests\Contoso.Api.Tests.csproj
    dotnet add .\Contoso.Api.Tests\Contoso.Api.Tests.csproj reference .\Contoso.Api\Contoso.Api.csproj

## C# Sprachreferenz: moderne Features und Entwurfsmuster C# language reference: modern features and design patterns

Feature Feature | Nutzen Value | Beispiel Example | Hinweis Note
--- | --- | --- | ---
Records Records | Wertorientierte DTOs und unveränderliche Modelle Value-oriented DTOs and immutable models | public record UserDto(string Id, string Name); public record UserDto(string Id, string Name); | Mit with-Ausdrücken und value equality kombinierbar Works with with-expressions and value equality
Primary Constructors Primary constructors | Kompakte Initialisierung in Klassen Compact initialization in classes | public class Mailer(IOptions<MailSettings> options) { } public class Mailer(IOptions<MailSettings> options) { } | Abhängigkeiten klar und sparsam halten Keep dependencies clear and minimal
Nullable Reference Types Nullable reference types | Vermeidet NullReference-Fehler früh Avoids NullReference errors early | string? name string? name | Warnings nicht blind unterdrücken Do not suppress warnings blindly
Pattern Matching Pattern matching | Lesbare Typ- und Zustandsprüfungen Readable type and state checks | if (result is { IsSuccess: true, Value: var data }) if (result is { IsSuccess: true, Value: var data }) | Mit switch expressions sehr mächtig Very powerful with switch expressions
Async/Await Async/await | Asynchrone I/O und Skalierung Asynchronous I/O and scalability | await db.SaveChangesAsync(); await db.SaveChangesAsync(); | ConfigureAwait im Library-Kontext bewusst einsetzen Use ConfigureAwait deliberately in library code
LINQ LINQ | Deklarative Datenabfragen Declarative data queries | orders.Where(o => o.IsOpen).Select(o => o.Id) orders.Where(o => o.IsOpen).Select(o => o.Id) | Deferred execution verstehen Understand deferred execution
Source Generators Source generators | Code zur Compile-Zeit erzeugen Generate code at compile time | System.Text.Json contexts System.Text.Json contexts | Nützlich für Performance und Boilerplate-Reduktion Useful for performance and reducing boilerplate
Collection Expressions Collection expressions | Kompaktere Initialisierung More compact initialization | int[] values = [1, 2, 3]; int[] values = [1, 2, 3]; | Neuere Sprachversion erforderlich Requires a recent language version

C# C#

    public record ApiResult<T>(bool IsSuccess, T? Value, string? Error);

    public static string ToBadge(ApiResult<int> result) =>
        result switch
        {
            { IsSuccess: true, Value: > 100 } => "High",
            { IsSuccess: true } => "Normal",
            { Error: not null } => "Failed",
            _ => "Unknown"
        };

## ASP.NET Core: Hosting, Middleware, Auth und moderne App-Modelle ASP.NET Core: hosting, middleware, auth, and modern app models

Bereich Area | Optionen Options | Wann einsetzen When to use | Hinweis Note
--- | --- | --- | ---
Minimal APIs Minimal APIs | Kompakte Endpoint-Definitionen Compact endpoint definitions | Services, micro APIs, internal tools Services, micro APIs, internal tools | Mit route groups und filters strukturieren Structure with route groups and filters
Controllers Controllers | Attribute routing, filters, conventions Attribute routing, filters, conventions | Komplexe APIs und größere Teams Complex APIs and larger teams | Geeignet für versionierte API-Flächen Well suited to versioned API surfaces
Razor Pages Razor Pages | Serverseitige UI-Seiten Server-side UI pages | Backoffice- oder admin-nahe Webapps Back-office or admin-adjacent web apps | PageModel-Logik schlank halten Keep PageModel logic lean
Blazor Server Blazor Server | Interaktive UI mit Server-State Interactive UI with server state | Internal dashboards, fast delivery Internal dashboards, fast delivery | SignalR-Connection-Management bedenken Consider SignalR connection management
Blazor WebAssembly Blazor WebAssembly | Clientseitige .NET UI Client-side .NET UI | Rich SPAs with .NET stack Rich SPAs with .NET stack | Payload und API-Security sauber designen Design payload and API security carefully
gRPC gRPC | Performante Service-to-Service-Kommunikation High-performance service-to-service communication | Internal contracts, streaming Internal contracts, streaming | HTTP/2 und tooling constraints beachten Observe HTTP/2 and tooling constraints
SignalR SignalR | Realtime Push-Kommunikation Real-time push communication | Chats, notifications, dashboards Chats, notifications, dashboards | Scale-out und auth token renewal einplanen Plan scale-out and auth token renewal
Microsoft Identity Web Microsoft Identity Web | Entra-ID-Auth für Web Apps und APIs vereinfachen Simplifies Entra ID auth for web apps and APIs | OpenID Connect, downstream APIs OpenID Connect, downstream APIs | Ideal für Graph- oder downstream token acquisition Ideal for Graph or downstream token acquisition

C# C#

    var builder = WebApplication.CreateBuilder(args);

    builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
        .AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd"));

    builder.Services.AddAuthorization(options =>
    {
        options.AddPolicy("RequireAdmin", policy => policy.RequireRole("Admin"));
    });

    var app = builder.Build();
    app.UseAuthentication();
    app.UseAuthorization();
    app.MapGet("/healthz", () => Results.Ok(new { status = "ok" }));
    app.Run();

## Entity Framework Core: Modellierung, Migrations und Performance Entity Framework Core: modeling, migrations, and performance

EF-Core-Thema EF Core topic | Beschreibung Description | Best Practice Best practice | Hinweis Note
--- | --- | --- | ---
DbContext DbContext | Unit of Work und Change Tracker Unit of work and change tracker | Kurzlebig per request oder operation Keep it short-lived per request or operation | Nicht als Singleton registrieren Do not register as singleton
Migrations Migrations | Schemaänderungen versionieren Version schema changes | Migration review und idempotent scripts Review migrations and generate idempotent scripts | Keine Produktionsdatenfixes blind in Migration packen Do not blindly put data fixes into migrations
Compiled Queries Compiled queries | Weniger Overhead bei Hot Paths Less overhead on hot paths | EF.CompileQuery for critical reads EF.CompileQuery for critical reads | Nur bei wirklich heißen Pfaden nötig Needed only for truly hot paths
Split Queries Split queries | Reduziert Cartesian explosion bei Includes Reduces cartesian explosion on includes | AsSplitQuery() AsSplitQuery() | Mehr round trips, aber oft weniger Datenmenge More round trips, but often less data volume
NoTracking NoTracking | Schnellere Read-only Queries Faster read-only queries | AsNoTracking() AsNoTracking() | Für Updates bewusst wieder Tracking aktivieren Re-enable tracking intentionally for updates
Providers Providers | SQL Server, PostgreSQL, SQLite, Cosmos DB SQL Server, PostgreSQL, SQLite, Cosmos DB | Provider-specific behaviors Provider-specific behaviors | SQL-Generierung und Datentypmapping pro Provider validieren Validate SQL generation and type mapping per provider

C# C#

    public class AppDbContext(DbContextOptions<AppDbContext> options) : DbContext(options)
    {
        public DbSet<Order> Orders => Set<Order>();

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Order>()
                .HasIndex(o => new { o.CustomerId, o.CreatedUtc });
        }
    }

## Visual Studio, VS Code, NuGet, Tests, Container und CI/CD Visual Studio, VS Code, NuGet, tests, containers, and CI/CD

Bereich Area | Wichtige Punkte Key points | Werkzeuge Tools | Hinweis Note
--- | --- | --- | ---
Visual Studio Visual Studio | Community, Professional, Enterprise; Debugging, profiling, Live Share Community, Professional, Enterprise; debugging, profiling, Live Share | Diagnostic Tools, Test Explorer, Snapshot Debugger Diagnostic Tools, Test Explorer, Snapshot Debugger | Enterprise-Features gegen Lizenzbedarf abgleichen Map enterprise features to license needs
VS Code VS Code | Leichter Editor mit C# Dev Kit, tasks.json, launch.json Lightweight editor with C# Dev Kit, tasks.json, launch.json | Extensions marketplace, Remote Development Extensions marketplace, Remote Development | Für containerisierte und polyglotte Projekte sehr stark Very strong for containerized and polyglot projects
NuGet NuGet | Paketquellen, lock files, private feeds, Azure Artifacts Package sources, lock files, private feeds, Azure Artifacts | dotnet add package, Package Manager Console dotnet add package, Package Manager Console | Supply-chain security und SBOM berücksichtigen Consider supply-chain security and SBOM
Testing Testing | xUnit, NUnit, MSTest, Moq, integration testing xUnit, NUnit, MSTest, Moq, integration testing | WebApplicationFactory, Testcontainers WebApplicationFactory, Testcontainers | Integrationstests auf reale Infrastrukturpfade ausrichten Aim integration tests at realistic infrastructure paths
Containerization Containerization | Dockerfile, Compose, .NET Aspire, AKS/Container Apps Dockerfile, Compose, .NET Aspire, AKS/Container Apps | Multi-stage builds, distroless images Multi-stage builds, distroless images | Trimming, globalization und diagnostics bewusst testen Test trimming, globalization, and diagnostics deliberately
GitHub Actions GitHub Actions | Build, test, pack, publish Build, test, pack, publish | actions/setup-dotnet, cache, artifacts actions/setup-dotnet, cache, artifacts | Secrets, environments und provenance sauber verwalten Manage secrets, environments, and provenance cleanly
Azure SDK Azure SDK | Azure.Identity, Storage, Messaging, AI SDKs Azure.Identity, Storage, Messaging, AI SDKs | DefaultAzureCredential, BlobServiceClient, ServiceBusClient DefaultAzureCredential, BlobServiceClient, ServiceBusClient | Credential chain und retries verstehen Understand the credential chain and retries

YAML YAML

    name: dotnet-ci

    on:
      push:
        branches: [ main ]
      pull_request:

    jobs:
      build:
        runs-on: ubuntu-latest
        steps:
          - uses: actions/checkout@v4
          - uses: actions/setup-dotnet@v4
            with:
              dotnet-version: '8.0.x'
          - run: dotnet restore
          - run: dotnet build --configuration Release --no-restore
          - run: dotnet test --configuration Release --no-build

Dockerfile Dockerfile

    FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
    WORKDIR /src
    COPY . .
    RUN dotnet publish src/Contoso.Api/Contoso.Api.csproj -c Release -o /app/publish

    FROM mcr.microsoft.com/dotnet/aspnet:8.0
    WORKDIR /app
    COPY --from=build /app/publish .
    ENTRYPOINT ["dotnet", "Contoso.Api.dll"]