Fetching contributors…
Cannot retrieve contributors at this time
78 lines (58 sloc) 2.66 KB

Getting Started

Npgsql has an Entity Framework (EF) Core provider. It behaves like other EF Core providers (e.g. SQL Server), so the general EF Core docs apply here as well. If you're just getting started with EF Core, those docs are the best place to start.

Development happens in the Npgsql.EntityFrameworkCore.PostgreSQL repository, all issues should be reported there.

Configuring the project file

To use the Npgsql EF Core provider, add a dependency on Npgsql.EntityFrameworkCore.PostgreSQL. You can follow the instructions in the general EF Core Getting Started docs.

Below is a .csproj file for a console application that uses the Npgsql EF Core provider:

<Project Sdk="Microsoft.NET.Sdk">
    <PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="2.1.0" />

Defining a DbContext

using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;

namespace ConsoleApp.PostgreSQL
    public class BloggingContext : DbContext
        public DbSet<Blog> Blogs { get; set; }
        public DbSet<Post> Posts { get; set; }
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
            => optionsBuilder.UseNpgsql("Host=my_host;Database=my_db;Username=my_user;Password=my_pw");

    public class Blog
        public int BlogId { get; set; }
        public string Url { get; set; }

        public List<Post> Posts { get; set; }

    public class Post
        public int PostId { get; set; }
        public string Title { get; set; }
        public string Content { get; set; }

        public int BlogId { get; set; }
        public Blog Blog { get; set; }

Additional configuration for ASP.NET Core applications

Modify the ConfigureServices method in Startup.cs:

public IServiceProvider ConfigureServices(IServiceCollection services)
    => services.AddEntityFrameworkNpgsql()

Using an Existing Database (Database-First)

The Npgsql EF Core provider also supports reverse-engineering a code model from an existing PostgreSQL database ("database-first"). To do so, use dotnet CLI to execute the following:

dotnet ef dbcontext scaffold "Host=my_host;Database=my_db;Username=my_user;Password=my_pw" Npgsql.EntityFrameworkCore.PostgreSQL