Zum Hauptinhalt springen

Razor Pages mit Postgres đź‘Ť

Docker-Compose file für die DB​

  • Datenbank in Docker starten
version: "3.9"

services:
db:
image: postgres
restart: always
environment:
POSTGRES_USER: hoell
POSTGRES_PASSWORD: 123
#POSTGRES_DB: MyDB
volumes:
- ./data:/var/lib/postgresql/data
ports:
- 5432:5432

pgadmin:
image: dpage/pgadmin4
restart: always
environment:
PGADMIN_DEFAULT_EMAIL: hoell@hl-dev.de
PGADMIN_DEFAULT_PASSWORD: 123
ports:
- 80:80

Datenbank erstellen​

  • Mit pgadmin verbinden

PG Admin

  • und DB erstellen

Create DB

Create DB

Projekt in Visual Studio erstellen​

  • ASP.NET Core Web App (Model-View-Controller)
  • Authentification Type: Individuel Accounts

Pakete installieren​

  • nicht erforderliche Packte löschen und erforderliche installieren ĂĽber den Paket Manager
Uninstall-Package Microsoft.EntityFrameworkCore.SqlServer
Install-Package Npgsql.EntityFrameworkCore.PostgreSQL -Version 6.0.8

Weitere Anpassungen​

  • in appsettings.json Default connection anpassen

Vorher​

{
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=aspnet-de.devcodemonkey.MVCPostgres-e9080d14-56b6-4db5-a52f-786892b2b818;Trusted_Connection=True;MultipleActiveResultSets=true"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}

Nachher​

{
"ConnectionStrings": {
"DefaultConnection": "Host=localhost;Database=MyDB;Port=5432;User Id=hoell;Password=123"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}

Program.cs anpassen​

Vorher​

builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(connectionString));

Nachher​

//builder.Services.AddDbContext<ApplicationDbContext>(options =>
// options.UseSqlServer(connectionString));
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseNpgsql(connectionString));

Alte Migrationsdatei löschen​

  • 00000000000000_CreateIdentitySchema.cs und ApplicationDbContextModelSnapshot.cs unter Data\Migrations löschen

Neue Migration erstellen über den Package Manage​

Add-Migration CreateIdentitySchema
Update-Database

Projekt starten und fertig :-)


Kommentare