Connecting ASP.NET Core with PostgreSQL

Aug 26, 2024

ASP.NET Core and PostgreSQL Connection

Overview

  • Topic: Connecting ASP.NET Core to PostgreSQL
  • Project: Student Management System
  • Framework Used: .NET 6

Project Setup

  • Create a new ASP.NET Core web application using the Model-View-Controller (MVC) template.
  • Initial configurations include:
    • Program.cs
    • appsettings.json (where database connections are stored)

Domain Class Creation

  • Define a domain class for the student named Student:
    • Properties include:
      • ID (Primary Key)
      • FirstName
      • MiddleName
      • LastName
      • FullName (combination of first, middle, and last names)
      • Gender (nullable)

Setting Up the Database Context

  • Create a folder named Context and define a class named ApplicationDbContext that derives from DbContext.
  • Install Entity Framework Core and its PostgreSQL provider package (Npgsql.EntityFrameworkCore.PostgreSQL).

Database Connection Configuration

  • In appsettings.json, define the connection string for PostgreSQL:
    • Example:
      "ConnectionStrings": {
        "DefaultConnection": "Host=localhost;Port=5432;Database=University;Username=postgres;Password=yourpassword"
      }  
      
  • Register the ApplicationDbContext in Program.cs:
    • Use builder.Services.AddDbContext<ApplicationDbContext>(options => options.UseNpgsql(connectionString));

Database Creation

  • Create the database named University using PostgreSQL interface.
  • After database creation, check to ensure no tables exist initially.

Entity Migration

  • Create the initial migration for the Student table:
    • Command: Add-Migration InitialMigration
    • Update the database: Update-Database
  • Changes made to connect to PostgreSQL vs. MS SQL Server include service configuration and NuGet packages used.

CRUD Operations

  • Scaffolding the Student Controller:
    • Use scaffolding to create a controller with views for the Student model:
      • This will include Create, Read, Update, Delete (CRUD) operations.
  • Launch application to test CRUD functionalities:
    • Create a new student entry and verify it is saved in the database.
  • Edit and delete records, confirming changes reflect in PostgreSQL.

Conclusion

  • Successfully demonstrated how to create a CRUD operation using ASP.NET Core with PostgreSQL.
  • Reminder to engage with content: Subscribe, share, and comment on future topics.