.NET

  • dotnet new
    • dotnet new list
    • dotnet new gitignore adds a .gitignore to the current directory.
# View .NET installed versions and information.
dotnet --info
# Restore packages.
dotnet restore

dotnet watch run

Environment variables

# launchSettings.json can typically set these.
# See https://learn.microsoft.com/en-us/aspnet/core/fundamentals/environments?view=aspnetcore-7.0#development-and-launchsettingsjson
$Env:ASPNETCORE_ENVIRONMENT = "Development"
$Env:NETCORE_ENVIRONMENT = "Development"

The ASPNETCORE_ENVIRONMENT value overrides DOTNET_ENVIRONMENT.

Entity Framework Core Tools

CLI reference.

# Install a tool globally.
dotnet tool install --global dotnet-ef

# Update a tool to the latest version.
dotnet tool update --global dotnet-ef

# List installed tools.
dotnet tool list -g

# Search for tools matching `searchTerm`.
dotnet tool search searchTerm

Add SQLite

dotnet add package Microsoft.EntityFrameworkCore.Sqlite
dotnet add package Microsoft.EntityFrameworkCore.Design

appsettings.json

{
  "ConnectionStrings": {
    "DefaultConnection": "Data source=./Database/name.db"
  }
}

Data/DataContext.cs

using API.Models;
using Microsoft.EntityFrameworkCore;

namespace API.Data
{
    public class DataContext : DbContext
    {
        public DbSet<Thing> Things { get; set; }

        public DataContext(DbContextOptions options) : base(options) { }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
        }
    }
}

Program.cs

// Add near the top.
builder.Services.AddDbContext<DataContext>(options =>
{
    options.UseSqlite(builder.Configuration.GetConnectionString("DefaultConnection"));
});

// Optional: apply migrations on startup. Add after builder.Build().
using (var scope = app.Services.CreateScope()) {
    var db = scope.ServiceProvider.GetRequiredService<DataContext>();
    db.Database.Migrate();
}

Create Initial Migration

dotnet ef migrations add InitialCreate -o Data/Migrations
dotnet ef database update