Monday, November 11, 2024

.Net Core connect to postgresql

 1. appsettings.json

  "ConnectionStrings": {
    "DefaultConnection": ""
  }

2. Program.cs
builder.Services.AddDbContext<ApiDbCopntext>(options => options.UseNpgsql(builder.Configuration.GetConnectionString("DefaultConnection")));

3. Models/ folder
add Table Class
namespace ReactAPIApp.Server.Models
{
    public class Driver
    {
        public int Id { get; set; }
        public string Name { get; set; } = null!;
        public int DriverNumber { get; set; }
    }
}

4. Add Context for example add Data folder

Data/ApiDbContext.cs

using Microsoft.EntityFrameworkCore;

using ReactAPIApp.Server.Models;

namespace ReactAPIApp.Server.Data
{
    public class ApiDbContext : DbContext
    {
        public ApiDbContext(DbContextOptions<ApiDbContext> options) : base(options){}
        public DbSet<Driver> Drivers { get; set; }
    }
}

5. run migrate command
if from package manager console
PM> Add-Migration initial

if from package manager console

No comments: