Skip to content

Instantly share code, notes, and snippets.

@farukcan
Last active February 23, 2023 22:19
Show Gist options
  • Save farukcan/9457968684dafcfedac5e50f10fb5858 to your computer and use it in GitHub Desktop.
Save farukcan/9457968684dafcfedac5e50f10fb5858 to your computer and use it in GitHub Desktop.
Postgres Dotnet Core
  • Auto create Context by Visual Studio. (Connected Services -> Add -> PostgreSQL)
  • Install NuGet package : Microsoft.EntityFrameworkCore
  • Install NuGet package : Npgsql.EntityFrameworkCore.PostgreSQL
  • Add code :
builder.Services.AddDbContext<LocationAppContext>(options =>
    options.UseNpgsql(System.Environment.GetEnvironmentVariable("POSTGRESQL_STRING") ?? throw new InvalidOperationException("Connection string 'LocationAppContext' not found."),
    options => options.EnableRetryOnFailure().SetPostgresVersion(new Version(9, 6))
    ));
  • Add [Key] notation for Id props
  • Set Postgres version to 9.6 (to prevent GENERATED error)
  • Sample Context.cs below (if required)
using LocationApp.Models;

namespace LocationApp.Data
{
    public class LocationAppContext : DbContext
    {
        public LocationAppContext (DbContextOptions<LocationAppContext> options)
            : base(options)
        {
        }

        public DbSet<LocationApp.Models.LocationData> LocationData { get; set; } = default!;
    }
}
  • Install : dotnet tool install --global dotnet-ef
  • Create migration : dotnet ef migrations add Mig
  • Update Database : dotnet ef database update
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment