Npgsql Entity Framework Core provider for PostgreSQL

repository·main·Indexed 23 days ago

https://github.com/npgsql/efcore.pg

An open-source Entity Framework Core provider that enables .NET developers to interact with PostgreSQL databases using LINQ and standard EF Core patterns. Built on top of the Npgsql ADO.NET provider, it supports PostgreSQL-specific features such as JSON, array, and range columns. Optional plugins provide extended capabilities, including PostGIS spatial data support via NetTopologySuite and date/time handling via NodaTime.

Tokens
2.4K
Snippets
5
Records
8
Agent score
82%

What's inside Npgsql.EntityFrameworkCore.PostgreSQL

  1. How NetTopologySuite spatial translation works

    main
    When using the NetTopologySuite plugin, the provider translates many NetTopologySuite methods and properties used in LINQ queries into their corresponding PostGIS operations in PostgreSQL. This allows for efficient spatial querying using standard .NET syntax.
  2. Use PostgreSQL-specific capabilities in EF Core

    main

    Beyond standard EF Core support, this provider enables querying PostgreSQL-specific data types and features, including:

    • JSON columns
    • Array columns
    • Range columns
    • Other advanced PostgreSQL features
  3. Quickstart with Npgsql Entity Framework Core provider

    main

    To use the Npgsql EF Core provider, define a DbContext and configure it using the UseNpgsql method within OnConfiguring. You can then perform standard EF Core operations like adding entities and querying data using LINQ. The provider is built on top of Npgsql and supports PostgreSQL-specific features like JSON, array, and range column querying.

    await using var ctx = new BlogContext();
    await ctx.Database.EnsureDeletedAsync();
    await ctx.Database.EnsureCreatedAsync();
    
    // Insert a Blog
    ctx.Blogs.Add(new() { Name = "FooBlog" });
    await ctx.SaveChangesAsync();
    
    // Query all blogs who's name starts with F
    var fBlogs = await ctx.Blogs.Where(b => b.Name.StartsWith("F")).ToListAsync();
    
    public class BlogContext : DbContext
    {
        public DbSet<Blog> Blogs { get; set; }
    
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
            => optionsBuilder.UseNpgsql(@"Host=myserver;Username=mylogin;Password=mypass;Database=mydatabase");
    }
    
    public class Blog
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
  4. Use NetTopologySuite for spatial data in EF Core

    main

    The Npgsql.EntityFrameworkCore.PostgreSQL.NetTopologySuite plugin enables support for PostgreSQL PostGIS spatial data within EF Core. It allows you to map NetTopologySuite types (like Point) directly to PostgreSQL spatial columns.

    To enable this support, call UseNetTopologySuite() within the UseNpgsql configuration method in your DbContext.OnConfiguring implementation. You can then use NetTopologySuite types as properties in your entity classes.

    public class BlogContext : DbContext
    {
        public DbSet<City> Cities { get; set; }
    
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
            => optionsBuilder.UseNpgsql(
                @"Host=myserver;Username=mylogin;Password=mypass;Database=mydatabase",
                o => o.UseNetTopologySuite());
    }
    
    public class City
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public Point Center { get; set; }
    }
    
    // Usage example
    await using var ctx = new BlogContext();
    await ctx.Database.EnsureCreatedAsync();
    
    // Insert a City with a NetTopologySuite Point
    ctx.Cities.Add(new()
    {
        Name = "FooCity",
        Center = new Point(10, 10)
    });
    await ctx.SaveChangesAsync();
    
    // Query using LINQ with spatial types
    var cities = await ctx.Cities.Where(b => b.Center == new Point(10, 10)).ToListAsync();
  5. Get started with Npgsql Entity Framework Core provider

    main

    Npgsql.EntityFrameworkCore.PostgreSQL is an open-source EF Core provider for PostgreSQL that allows you to interact with your database using LINQ syntax. It is built on top of the Npgsql ADO.NET provider. To use it, configure your DbContext using the UseNpgsql method within OnConfiguring and provide a valid PostgreSQL connection string.

    await using var ctx = new BlogContext();
    await ctx.Database.EnsureDeletedAsync();
    await ctx.Database.EnsureCreatedAsync();
    
    // Insert a Blog
    ctx.Blogs.Add(new() { Name = "FooBlog" });
    await ctx.SaveChangesAsync();
    
    // Query all blogs who's name starts with F
    var fBlogs = await ctx.Blogs.Where(b => b.Name.StartsWith("F")).ToListAsync();
    
    public class BlogContext : DbContext
    {
        public DbSet<Blog> Blogs { get; set; }
    
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
            => optionsBuilder.UseNpgsql(@"Host=myserver;Username=mylogin;Password=mypass;Database=mydatabase");
    }
    
    public class Blog
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
  6. Use NodaTime with Npgsql Entity Framework Core provider

    main

    The EFCore.PG.NodaTime plugin allows you to use the NodaTime date/time library for your entity properties when interacting with PostgreSQL. This provides a safer and more robust API for handling date and time data compared to standard .NET types.

    To enable NodaTime support, call UseNodaTime() within the UseNpgsql configuration options in your DbContext.OnConfiguring method. Once configured, you can use NodaTime types like Instant directly in your entity classes and use them within LINQ queries. The plugin translates most NodaTime methods and properties into the appropriate PostgreSQL date/time operations.

    public class BlogContext : DbContext
    {
        public DbSet<Blog> Blogs { get; set; }
    
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
            => optionsBuilder.UseNpgsql(
                @"Host=myserver;Username=mylogin;Password=mypass;Database=mydatabase",
                o => o.UseNodaTime());
    }
    
    public class Blog
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public Instant CreationTime { get; set; }
    }
    
    // Usage example
    await using var ctx = new BlogContext();
    await ctx.Database.EnsureCreatedAsync();
    
    // Insert
    ctx.Blogs.Add(new()
    {
        Name = "FooBlog",
        CreationTime = SystemClock.Instance.GetCurrentInstant()
    });
    await ctx.SaveChangesAsync();
    
    // Query using NodaTime types
    var newBlogs = await ctx.Blogs
        .Where(b => b.CreationTime >= Instant.FromUtc(2020, 1, 1, 0, 0, 0))
        .ToListAsync();
  7. Configure Npgsql in DbContext

    main

    To connect your EF Core context to a PostgreSQL database, override the OnConfiguring method in your DbContext class and call optionsBuilder.UseNpgsql with a valid Npgsql connection string.

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        => optionsBuilder.UseNpgsql(@"Host=myserver;Username=mylogin;Password=mypass;Database=mydatabase");
  8. Install related Npgsql EF Core plugins

    main

    Depending on your requirements, you may need additional plugins to extend the provider's capabilities:

    • PostGIS Support: Use Npgsql.EntityFrameworkCore.PostgreSQL.NetTopologySuite for spatial data support.
    • NodaTime Support: Use Npgsql.EntityFrameworkCore.PostgreSQL.NodaTime to use NodaTime date/time types with PostgreSQL.
    • Base Provider: This package requires the underlying Npgsql ADO.NET provider (Npgsql).