Instruction file imported from paonath/PH.DapperUtils.UnitOfWork (
.github/instructions/dotnet.cli.instructions.md). Copyright stays with the author.
dotnet CLI — Comandi rapidi
Scopo: promemoria rapido dei comandi .NET CLI più usati (SDK .NET 6/7/8/10+).
Verifica installazione
- Info:
dotnet --info— mostra SDK, runtime e dettagli dell'installazione. - SDK / Runtimes:
dotnet --list-sdks,dotnet --list-runtimes
Creare progetti / soluzioni
- Nuovo progetto:
dotnet new <template> -n <Name>
Esempio:dotnet new webapi -n MyApi - Nuova soluzione:
dotnet new sln -n MySolution - Aggiungi progetto alla soluzione:
dotnet sln MySolution.sln add MyApi/MyApi.csproj
Restore / Build / Run / Test
- Restore:
dotnet restore [<proj|sln>](implicit inbuild,run,test,publish) - Build:
dotnet build [<proj|sln>] -c Release - Run:
dotnet run --project <proj> - Test:
dotnet test [<proj|sln>] -c Release
Pubblicazione / Packaging
- Publish:
dotnet publish <proj> -c Release -o ./publish - Pack (NuGet):
dotnet pack <proj> -c Release - Push NuGet:
dotnet nuget push <nupkg> --api-key <key> -s https://api.nuget.org/v3/index.json
Gestione pacchetti / riferimenti
- Aggiungi pacchetto:
dotnet add <proj> package <PackageName> --version <version> - Rimuovi pacchetto:
dotnet remove <proj> package <PackageName> - Aggiungi riferimento progetto:
dotnet add <proj> reference ../Other/Other.csproj
Tool e workload
- Global tool:
dotnet tool install --global <tool> - Aggiorna tool:
dotnet tool update --global <tool> - Lista tool globali:
dotnet tool list --global - Local tool (tool-path):
dotnet tool install --tool-path ./tools <tool> - Workloads:
dotnet workload install <workload>
Entity Framework (CLI)
- Installa:
dotnet tool install --global dotnet-ef - Migrazione:
dotnet ef migrations add <Name> --project <proj> --startup-project <proj> - Applica:
dotnet ef database update --project <proj> --startup-project <proj>
Hot-reload / watch
dotnet watch run --project <proj>
User secrets (per progetto)
dotnet user-secrets init --project <proj>dotnet user-secrets set "Key" "Value" --project <proj>
Comandi di utilità
dotnet cleandotnet msbuild(passa opzioni MSBuild con-p:<NAME>=<VALUE>)dotnet sdk check(verifica aggiornamenti SDK)
Esempi rapidi
dotnet new sln -n MySolution
dotnet new webapi -n MyApi
dotnet sln MySolution.sln add MyApi/MyApi.csproj
dotnet restore
dotnet build -c Release
dotnet run --project MyApi
Risorse
- Documentazione ufficiale: https://learn.microsoft.com/dotnet/core/tools/
- EF Core CLI: https://learn.microsoft.com/ef/core/cli/dotnet
Note: la maggior parte dei comandi esegue implicitamente dotnet restore; usare --no-restore se necessario.
description: 'Best practices and rules for using the .NET CLI (dotnet) in C# projects and solutions.' applyTo: '**/.csproj, **/.sln, **/*.slnx, /Migrations/, **/Program.cs'
.NET CLI Instructions
Guidelines for using the dotnet CLI correctly in .NET C# projects.
The target framework version (-f) must be chosen per project based on the project's requirements — do not assume a single version for the entire solution.
Reference: https://learn.microsoft.com/dotnet/core/tools/
General Rules
- Always run
dotnetcommands from the correct working directory (usually the solution root or a specific project folder). - Use
-hor--helpon any command to discover its options:dotnet <command> --help. - Prefer
dotnet buildover manually restoring first; restore is implicit in most commands. - Always use
-c Releasefor production builds and publishes. - Use
--no-restoreonly in CI pipelines where restore has already run in a prior step.
Solution Management
# Create a new solution
dotnet new sln -n SolutionName
# Add a project to the solution
dotnet sln add Path/To/Project.csproj
# Remove a project from the solution
dotnet sln remove Path/To/Project.csproj
# List projects in the solution
dotnet sln list
# Migrate .sln to .slnx format
dotnet sln migrate
Project Creation
Use the following templates for new projects:
| Need | Template command |
|---|---|
| Minimal API / Web API | dotnet new webapi -n Name -f <tfm> |
| Web API with controllers | dotnet new webapi -n Name -f <tfm> --use-controllers |
| Class Library (DAL, Models) | dotnet new classlib -n Name -f <tfm> |
| Console App | dotnet new console -n Name -f <tfm> |
| Worker Service | dotnet new worker -n Name -f <tfm> |
| xUnit Test Project | dotnet new xunit -n Name -f <tfm> |
Where <tfm> is the Target Framework Moniker for that specific project (e.g. net9.0, net8.0, netstandard2.1).
Rules:
- Always include
-f <tfm>to pin the target framework — never rely on the SDK default. - Determine the framework version per project: check the existing solution's
.csprojfiles and ask if unclear. Do not assume all projects use the same version. - Use
netX.0for applications and libraries targeting .NET; usenetstandard2.xonly for libraries that must support .NET Framework. - Use PascalCase with dots for project names:
MySolution.Api,MySolution.Dal. - After creating a project, immediately add it to the solution:
dotnet sln add.
Project References
# Add a project reference (prefer this over editing .csproj directly)
dotnet reference add ../Other.Project/Other.Project.csproj
# List references
dotnet reference list
# Remove a reference
dotnet reference remove ../Other.Project/Other.Project.csproj
Build
# Build the solution (Debug by default)
dotnet build MySolution.sln
# Build in Release
dotnet build MySolution.sln -c Release
# Full verbosity for diagnosing build errors
dotnet build -v detailed
Rules:
- Always build at the solution level, not just the project level, to catch dependency issues.
- Use
dotnet cleanbefore a full rebuild when there are unexplained issues.
Run and Watch
# Run a specific project
dotnet run --project MyProject.Api/MyProject.Api.csproj
# Run with hot reload (development)
dotnet watch --project MyProject.Api/MyProject.Api.csproj
# Pass custom arguments
dotnet run --project MyProject.ConsoleApp -- --arg value
Rules:
- Use
dotnet watchduring development for hot reload. - Use
--environment Developmentto ensure correct appsettings are loaded locally.
Publish
# Framework-dependent publish (requires .NET on target machine)
dotnet publish -c Release -o ./publish
# Self-contained for Windows x64
dotnet publish -c Release -r win-x64 --self-contained true -o ./publish
# Single-file executable
dotnet publish -c Release -r win-x64 --self-contained true /p:PublishSingleFile=true -o ./publish
Rules:
- Always use
-c Releasefor publishable artifacts. - Prefer framework-dependent for servers where the runtime is controlled.
- Use
--self-containedonly when the target environment lacks a .NET runtime.
Test
# Run all tests
dotnet test MySolution.sln
# Run with detailed output
dotnet test --logger "console;verbosity=detailed"
# Filter by test name
dotnet test --filter "FullyQualifiedName~MyClass"
# Collect code coverage
dotnet test --collect:"XPlat Code Coverage" --results-directory ./TestResults
Rules:
- Always run tests at the solution level.
- Use
--filterto run a subset during development; run the full suite before committing. - Use
Debugbuilds during active development to identify errors, examine stack traces and find code that needs to be implemented or changed; reserveReleasebuilds for initial smoke tests and final verification before shipping. - Never use
--no-buildin CI; always build before running tests.
NuGet Package Management
# Add a package (preferred modern syntax)
dotnet package add PackageName
# Add a specific version
dotnet package add PackageName --version 1.2.3
# Remove a package
dotnet package remove PackageName
# List installed packages
dotnet package list
# Check for outdated packages
dotnet package list --outdated
# Clear the NuGet cache
dotnet nuget locals all --clear
Rules:
- Always use
dotnet package addinstead of manually editing.csprojfiles. - Pin versions explicitly in production projects to avoid unexpected upgrades.
- Run
dotnet restoreafter manually editing.csprojpackage references. - Manage NuGet source credentials securely; never commit API keys.
Entity Framework Core
Setup
# Install dotnet-ef tool globally (required once per machine)
dotnet tool install --global dotnet-ef
# Add EF Core Design package to the DAL project
dotnet package add Microsoft.EntityFrameworkCore.Design --project Prada.Dal
Migrations
# Add a new migration
dotnet ef migrations add MigrationName --project Prada.Dal
# Add migration when startup project differs from DAL
dotnet ef migrations add MigrationName \
--project Prada.Dal \
--startup-project DotNetExample.ConsoleApp
# List existing migrations
dotnet ef migrations list --project Prada.Dal
# Remove the last (unapplied) migration
dotnet ef migrations remove --project Prada.Dal
# Remove without database connection
dotnet ef migrations remove --project Prada.Dal --offline
# Generate idempotent SQL script for all migrations
dotnet ef migrations script --project Prada.Dal --idempotent -o migrations.sql
Database
# Apply all pending migrations
dotnet ef database update --project Prada.Dal
# Apply up to a specific migration
dotnet ef database update TargetMigration --project Prada.Dal
# Rollback to a previous migration
dotnet ef database update PreviousMigration --project Prada.Dal
# Drop the database (development only)
dotnet ef database drop --project Prada.Dal --force
Rules:
- Always name migrations descriptively:
AddUserRoleTable,FixArticoloIndex. - Never remove a migration that has been applied to any shared or production database.
- Use
--idempotentSQL scripts for deployment to environments where the migration state is unknown. - Set
context.Authorandcontext.ContextIdentifierbeforeSaveChanges()to correctly populate audit logs.
User Secrets
# Initialize user secrets for a project
dotnet user-secrets init --project MyProject.Api
# Set a secret
dotnet user-secrets set "ConnectionStrings:DefaultConnection" "Server=...;" --project MyProject.Api
# List all secrets
dotnet user-secrets list --project MyProject.Api
# Remove a secret
dotnet user-secrets remove "ConnectionStrings:DefaultConnection" --project MyProject.Api
Rules:
- Use User Secrets for local development credentials; never commit connection strings or API keys.
- User Secrets require
<UserSecretsId>in the.csprojfile (added automatically bydotnet user-secrets init). - In production, use environment variables or Azure Key Vault instead of User Secrets.
Dev Certificates (HTTPS)
dotnet dev-certs https --trust # trust local HTTPS cert
dotnet dev-certs https --clean && dotnet dev-certs https --trust # reset
Tool Management
# Install a global tool
dotnet tool install --global dotnet-ef
# Update a global tool
dotnet tool update --global dotnet-ef
# List installed global tools
dotnet tool list --global
# Restore local tools from .config/dotnet-tools.json
dotnet tool restore
Rules:
- Use local tools (
.config/dotnet-tools.json) for team-shared tooling to ensure version consistency. - Commit
.config/dotnet-tools.jsonto source control. - Run
dotnet tool restorein CI pipelines before using any local tools.
Code Formatting
# Format the entire solution
dotnet format MySolution.sln
# Check without modifying files (use in CI)
dotnet format MySolution.sln --verify-no-changes
# Format only warnings
dotnet format MySolution.sln --severity warn
Rules:
- Run
dotnet format --verify-no-changesin CI to enforce code style. - Configure formatting rules in
.editorconfigat the solution root.
Anti-Patterns to Avoid
- Do NOT manually edit
<PackageReference>entries to add packages; usedotnet package add. - Do NOT run migrations directly against production databases without reviewing the generated SQL first.
- Do NOT run
dotnet ef database dropin any environment. - Do NOT commit
appsettings.Development.jsonwith real secrets; use User Secrets instead. - Do NOT use
--forceondotnet ef migrations removeif the migration may have been applied. - Do NOT omit
-f <tfm>when creating new projects — always specify the framework explicitly to avoid inheriting the SDK default, which may differ from the project's intended version.