Using Postgres with C#

Download full source code.

Using Postgres with C# is fairly straightforward, it can even be used with Entity Framework Core.

In an earlier post, I showed how to use Postgres with Docker, this is the easiest way to get Postgres up and running.

I use two packages when working with Postgres - Npgsql.EntityFrameworkCore.PostgreSQL, and EFCore.NamingConventions.

The EFCore.NamingConventions package is used to convert the C# property and class names to snake case, which is the common convention used in Postgres.

The code is very simple, so I won’t explain it here (other than the few comments), and the full source is available in the attached zip file.

This is the Program.cs file -

 1using EntityFrameworkPostgresDocker.Data;
 2using Microsoft.EntityFrameworkCore;
 3
 4SalesContext salesContext = new SalesContext(new DbContextOptionsBuilder<SalesContext>()
 5    .UseNpgsql("Host=localhost;Port=5432;Database=salesdb;Username=postgres;Password=postgres").Options); // connection string
 6
 7salesContext.Database.EnsureDeleted(); // delete the database if it exists
 8salesContext.Database.EnsureCreated(); // created the database
 9await salesContext.SeedAsync().ConfigureAwait(false); // seed the database, code in the zip file
10
11var products = salesContext.Products.ToList(); // get all products
12
13foreach (var product in products)
14{
15    Console.WriteLine(product);
16}

There, simple to get going with Postgres and C#.

Download full source code.

comments powered by Disqus

Related