From e5c164fe4c87220d1ca4c5ca12b4b0263d153b4e Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Thu, 26 Sep 2019 14:20:49 +0200 Subject: [PATCH 001/207] Bring in conceptual docs No longer take conceptual docs from the project repos. Closes #10 --- docs/index.md | 84 +++++++++ docs/mapping/array.md | 35 ++++ docs/mapping/enum.md | 74 ++++++++ docs/mapping/full-text-search.md | 131 ++++++++++++++ docs/mapping/general.md | 54 ++++++ docs/mapping/json.md | 236 ++++++++++++++++++++++++++ docs/mapping/nodatime.md | 50 ++++++ docs/mapping/nts.md | 124 ++++++++++++++ docs/mapping/range.md | 74 ++++++++ docs/miscellaneous.md | 118 +++++++++++++ docs/modeling/generated-properties.md | 116 +++++++++++++ docs/modeling/indexes.md | 49 ++++++ docs/modeling/table-column-naming.md | 32 ++++ docs/release-notes/1.1.md | 30 ++++ docs/release-notes/2.0.md | 19 +++ docs/release-notes/2.1.md | 81 +++++++++ docs/release-notes/2.2.md | 57 +++++++ docs/release-notes/3.0.md | 49 ++++++ docs/toc.md | 22 +++ 19 files changed, 1435 insertions(+) create mode 100644 docs/index.md create mode 100644 docs/mapping/array.md create mode 100644 docs/mapping/enum.md create mode 100644 docs/mapping/full-text-search.md create mode 100644 docs/mapping/general.md create mode 100644 docs/mapping/json.md create mode 100644 docs/mapping/nodatime.md create mode 100644 docs/mapping/nts.md create mode 100644 docs/mapping/range.md create mode 100644 docs/miscellaneous.md create mode 100644 docs/modeling/generated-properties.md create mode 100644 docs/modeling/indexes.md create mode 100644 docs/modeling/table-column-naming.md create mode 100644 docs/release-notes/1.1.md create mode 100644 docs/release-notes/2.0.md create mode 100644 docs/release-notes/2.1.md create mode 100644 docs/release-notes/2.2.md create mode 100644 docs/release-notes/3.0.md create mode 100644 docs/toc.md diff --git a/docs/index.md b/docs/index.md new file mode 100644 index 0000000000..bb32dcaee2 --- /dev/null +++ b/docs/index.md @@ -0,0 +1,84 @@ +[![stable](https://img.shields.io/nuget/v/Npgsql.EntityFrameworkCore.PostgreSQL.svg?label=stable)](https://www.nuget.org/packages/Npgsql.EntityFrameworkCore.PostgreSQL/) +[![unstable](https://img.shields.io/myget/npgsql-unstable/vpre/Npgsql.EntityFrameworkCore.PostgreSQL.svg?label=unstable)](https://www.myget.org/feed/npgsql-unstable/package/nuget/Npgsql.EntityFrameworkCore.PostgreSQL) +[![next patch](https://img.shields.io/myget/npgsql/v/Npgsql.EntityFrameworkCore.PostgreSQL.svg?label=next%20patch)](https://www.myget.org/feed/npgsql/package/nuget/Npgsql.EntityFrameworkCore.PostgreSQL) +[![appveyor](https://img.shields.io/appveyor/ci/roji/npgsql-entityframeworkcore-postgresql/dev.svg?label=appveyor)](https://ci.appveyor.com/project/roji/npgsql-entityframeworkcore-postgresql) +[![travis](https://img.shields.io/travis/npgsql/npgsql.svg?label=travis)](https://travis-ci.org/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL) +[![gitter](https://img.shields.io/badge/gitter-join%20chat-brightgreen.svg)](https://gitter.im/npgsql/npgsql) + +# 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](https://docs.microsoft.com/ef/core/index) 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](https://github.com/npgsql/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](https://docs.microsoft.com/ef/core/get-started/). + +Below is a `.csproj` file for a console application that uses the Npgsql EF Core provider: + +```xml + + + netcoreapp2.2 + + + + + +``` + +## Defining a `DbContext` + +```c# +using System.Collections.Generic; +using Microsoft.EntityFrameworkCore; + +namespace ConsoleApp.PostgreSQL +{ + public class BloggingContext : DbContext + { + public DbSet Blogs { get; set; } + public DbSet 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 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`: + +```c# +public IServiceProvider ConfigureServices(IServiceCollection services) + => services.AddEntityFrameworkNpgsql() + .AddDbContext() + .BuildServiceProvider(); +``` +## 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: + +```bash +dotnet ef dbcontext scaffold "Host=my_host;Database=my_db;Username=my_user;Password=my_pw" Npgsql.EntityFrameworkCore.PostgreSQL +``` diff --git a/docs/mapping/array.md b/docs/mapping/array.md new file mode 100644 index 0000000000..271bf8a614 --- /dev/null +++ b/docs/mapping/array.md @@ -0,0 +1,35 @@ +# Array Type Mapping + +PostgreSQL has the unique feature of supporting [*array data types*](https://www.postgresql.org/docs/current/static/arrays.html). This allow you to conveniently and efficiently store several values in a single column, where in other database you'd typically resort to concatenating the values in a string or defining another table with a one-to-many relationship. + +> [!NOTE] +> Although PostgreSQL supports multidimensional arrays, these aren't yet supported by the EF Core provider. + +# Mapping arrays + +Simply define a regular .NET array or `List<>` property, and the provider + +```c# +public class Post +{ + public int Id { get; set; } + public string Name { get; set; } + public string[] Tags { get; set; } + public List AlternativeTags { get; set; } +} +``` + +The provider will create `text[]` columns for the above two properties, and will properly detect changes in them - if you load an array and change one of its elements, calling `SaveChanges()` will automatically update the row in the database accordingly. + +# Operation translation + +The provider can also translate CLR array operations to the corresponding SQL operation; this allows you to efficiently work with arrays by evaluating operations in the database and avoids pulling all the data. The following table lists the range operations that currently get translated. If you run into a missing operation, please open an issue. + +Note that operation translation on `List<>` is limited at this time, but will be improved in the future. It's recommended to use an array for now. + +| C# expression | SQL generated by Npgsql | +|------------------------------------------------------------|-------------------------| +| `.Where(c => c.SomeArray[1] == "foo")` | [`WHERE "c"."SomeArray"[1] = 'foo'`](https://www.postgresql.org/docs/current/static/arrays.html#ARRAYS-ACCESSING) +| `.Where(c => c.SomeArray.SequenceEqual(new[] { 1, 2, 3 })` | [`WHERE "c"."SomeArray" = ARRAY[1, 2, 3])`](https://www.postgresql.org/docs/current/static/arrays.html) +| `.Where(c => c.SomeArray.Contains(3))` | [`WHERE 3 = ANY("c"."SomeArray")`](https://www.postgresql.org/docs/current/static/functions-comparisons.html#AEN21104) +| `.Where(c => c.SomeArray.Length == 3)` | [`WHERE cardinality("c"."SomeArray") = 3`](https://www.postgresql.org/docs/current/static/functions-array.html#ARRAY-FUNCTIONS-TABLE) diff --git a/docs/mapping/enum.md b/docs/mapping/enum.md new file mode 100644 index 0000000000..42a4ede376 --- /dev/null +++ b/docs/mapping/enum.md @@ -0,0 +1,74 @@ +# Enum Type Mapping + +By default, any enum properties in your model will be mapped to database integers. EF Core 2.1 also allows you to map these to strings in the database with value converters. + +However, the Npgsql provider also allows you to map your CLR enums to [database enum types](https://www.postgresql.org/docs/current/static/datatype-enum.html). This option, unique to PostgreSQL, provides the best of both worlds: the enum is internally stored in the database as a number (minimal storage), but is handled like a string (more usable, no need to remember numeric values) and has type safety. + +## Creating your database enum + +First, you must specify the PostgreSQL enum type on your model, just like you would with tables, sequences or other databases objects: + +# [Version 2.2](#tab/tabid-1) + +```c# +protected override void OnModelCreating(ModelBuilder builder) + => builder.ForNpgsqlHasEnum(); +``` + +# [Version 2.1](#tab/tabid-2) + +```c# +protected override void OnModelCreating(ModelBuilder builder) + => builder.ForNpgsqlHasEnum("Mood", new[] { "happy", "sad" }); +``` + +--- +
+ +This causes the EF Core provider to create your data enum type, `Mood`, with two labels: `happy` and `sad`. This will cause the appropriate migration to be created. + +## Mapping your enum + +Even if your database enum is created, Npgsql has to know about it, and especially about your CLR enum type that should be mapped to it. This is done by adding the following code, *before* any EF Core operations take place. An appropriate place for this is in the static constructor on your DbContext class: + +```c# +static MyDbContext() + => NpgsqlConnection.GlobalTypeMapper.MapEnum(); +``` + +This code lets Npgsql know that your CLR enum type, `Mood`, should be mapped to a database enum called `Mood`. + +If you're curious as to inner workings, this code maps the enum with the ADO.NET provider - [see here for the full docs](http://www.npgsql.org/doc/types/enums_and_composites.html). When the Npgsql EF Core first initializes, it calls into the ADO.NET provider to get all mapped enums, and sets everything up internally at the EF Core layer as well. + +## Using enum properties + +Once your enum is mapped and created in the database, you can use your CLR enum type just like any other property: + +```c# +public class Blog +{ + public int Id { get; set; } + public Mood Mood { get; set; } +} + +using (var ctx = new MyDbContext()) +{ + // Insert + ctx.Blogs.Add(new Blog { Mood = Mood.Happy }); + ctx.Blogs.SaveChanges(); + + // Query + var blog = ctx.Blogs.Single(b => b.Mood == Mood.Happy); +} +``` + +## Altering enum definitions + +Although PostgreSQL allows [altering enum types](https://www.postgresql.org/docs/current/static/sql-altertype.html), the Npgsql provider currently does not generate SQL for those operations (beyond creating and dropping the entire type). If you to add, remove or rename enum values, you'll have to include raw SQL in your migrations (this is quite easy to do). As always, test your migrations carefully before running them on production databases. + +## Scaffolding from an existing database + +If you're creating your model from an existing database, the provider will recognize enums in your database, and scaffold the appropriate `ForNpgsqlHasEnum()` lines in your model. However, since the scaffolding process has no knowledge of your CLR type, and will therefore skip your enum columns (warnings will be logged). You will have to create the CLR type, add the global mapping and add the properties to your entities. + +In the future it may be possible to scaffold the actual enum type (and with it the properties), but this doesn't happen at the moment. + diff --git a/docs/mapping/full-text-search.md b/docs/mapping/full-text-search.md new file mode 100644 index 0000000000..da790b1ab7 --- /dev/null +++ b/docs/mapping/full-text-search.md @@ -0,0 +1,131 @@ +# Full Text Search + +PostgreSQL has [built-in support for full-text search](https://www.postgresql.org/docs/current/static/textsearch.html), which allows you to conveniently and efficiently query natural language documents. + +## Mapping + +PostgreSQL full text search types are mapped onto .NET types built-in to Npgsql. The `tsvector` type is mapped to `NpgsqlTsVector` and `tsquery` is mapped to `NpgsqlTsQuery`. This means you can use properties of type `NpgsqlTsVector` directly in your model to create `tsvector` columns. The `NpgsqlTsQuery` type on the other hand, is used in LINQ queries. + +```c# +public class BlogPost +{ + public string Title { get; set; } + public string Content { get; set; } + public NpgsqlTsVector SearchVector { get; set; } +} +``` + +## Operation translation + +Almost all PostgreSQL full text search functions can be called through LINQ queries. All supported EF Core LINQ methods are defined in extension classes in the `Microsoft.EntityFrameworkCore` namespace, so simply referencing the Npgsql provider will light up these methods. Here is a table showing translations for some operations; if an operation you need is missing, please open an issue to request for it. + +| This C# expression... | ... gets translated to this SQL | +|----------------------------------------------------------|---------------------------------------------------------------------| +| .Select(c => EF.Functions.ToTsVector("english", c.Name)) | [SELECT to_tsvector('english'::regconfig, c."Name")](https://www.postgresql.org/docs/current/static/textsearch-controls.html#TEXTSEARCH-PARSING-DOCUMENTS) +| .Select(c => NpgsqlTsVector.Parse("b")) | [SELECT CAST('b' AS tsvector)](https://www.postgresql.org/docs/current/static/sql-expressions.html#SQL-SYNTAX-TYPE-CASTS) +| .Select(c => EF.Functions.ToTsQuery("english", "pgsql")) | [SELECT to_tsquery('english'::regconfig, 'pgsql')`](https://www.postgresql.org/docs/current/static/textsearch-controls.html#TEXTSEARCH-PARSING-QUERIES) +| .Select(c => NpgsqlTsQuery.Parse("b")) | [SELECT CAST('b' AS tsquery)](https://www.postgresql.org/docs/current/static/sql-expressions.html#SQL-SYNTAX-TYPE-CASTS) +| .Where(c => c.SearchVector.Matches("Npgsql")) | [WHERE c."SearchVector" @@ 'Npgsql'](https://www.postgresql.org/docs/current/static/textsearch-intro.html#TEXTSEARCH-MATCHING) +| .Select(c => EF.Functions.ToTsQuery(c.SearchQuery).ToNegative()) | [SELECT !! to_tsquery(c."SearchQuery")](https://www.postgresql.org/docs/current/static/textsearch-features.html#TEXTSEARCH-MANIPULATE-TSQUERY) +| .Select(c => EF.Functions.ToTsVector(c.Name).SetWeight(NpgsqlTsVector.Lexeme.Weight.A)) | [SELECT setweight(to_tsvector(c."Name"), 'A')](https://www.postgresql.org/docs/current/static/textsearch-features.html#TEXTSEARCH-MANIPULATE-TSVECTOR) + +## Setting up and querying a full text search index on an entity + +As [the PostgreSQL documentation](https://www.postgresql.org/docs/current/static/textsearch-tables.html) explains, full-text search requires an index to run efficiently. This section will show two ways to do this, both (currently) requiring raw SQL in your migrations. Read the PostgreSQL docs for more information on the different approaches. + +### Method 1: Expression index + +The simpler method to use full-text search is to set up an expression index. Let's take the following entity: + +```c# +public class Product +{ + public int Id { get; set; } + public string Name { get; set; } + public string Description { get; set; } +} +``` + +Create a migration which will contain the index creation SQL (`dotnet ef migrations add ...`). At this point, open the generated migration with your editor and add the following: + +```c# +protected override void Up(MigrationBuilder migrationBuilder) +{ + migrationBuilder.Sql(@"CREATE INDEX fts_idx ON ""Product"" USING GIN (to_tsvector('english', ""Name"" || ' ' || ""Description""));"); +} + +protected override void Down(MigrationBuilder migrationBuilder) + migrationBuilder.Sql(@"DROP INDEX fts_idx;"); +} +``` + +This will create a full-text search index on the `Name` and `Description` columns. You can query as follows: + +```c# +var context = new ProductDbContext(); +var npgsql = context.Products + .Where(p => EF.Functions.ToTsVector("english", p.Name + " " + p.Description).Matches("Npgsql")) + .ToList(); +``` + +### Method 2: tsvector column + +Instead of an expression index, this method will add a `tsvector` column on your table that updates itself with a trigger. + +First, add an `NpgsqlTsVector` property to your entity: + +```c# +public class Product +{ + public int Id { get; set; } + public string Name { get; set; } + public string Description { get; set; } + public NpgsqlTsVector SearchVector { get; set; } +} +``` + +and modify the `OnModelCreating()` of your context class to add an index as follows: + +```c# +protected override void OnModelCreating(ModelBuilder modelBuilder) +{ + modelBuilder.Entity() + .HasIndex(p => p.SearchVector) + .ForNpgsqlHasMethod("GIN"); // Index method on the search vector (GIN or GIST) +} +``` + +Now generate a migration (`dotnet ef migrations add ....`), and open it with your favorite editor, adding the following: + +```c# +public partial class CreateProductTable : Migration +{ + protected override void Up(MigrationBuilder migrationBuilder) + { + // Migrations for creation of the column and the index will appear here, all we need to do is set up the trigger to update the column: + + migrationBuilder.Sql( + @"CREATE TRIGGER product_search_vector_update BEFORE INSERT OR UPDATE + ON ""Products"" FOR EACH ROW EXECUTE PROCEDURE + tsvector_update_trigger(""SearchVector"", 'pg_catalog.english', ""Name"", ""Description"");"); + + // If you were adding a tsvector to an existing table, you should populate the column using an UPDATE + // migrationBuilder.Sql("UPDATE \"Products\" SET \"Name\" = \"Name\";"); + } + + protected override void Down(MigrationBuilder migrationBuilder) + { + // Migrations for dropping of the column and the index will appear here, all we need to do is drop the trigger: + migrationBuilder.Sql("DROP TRIGGER product_search_vector_update"); + } +} +``` + +Any inserts or updates on the `Products` table will now update the `SearchVector` column and maintain it automatically. You can query it as follows: + +```c# +var context = new ProductDbContext(); +var npgsql = context.Products + .Where(p => p.SearchVector.Matches("Npgsql")) + .ToList(); +``` diff --git a/docs/mapping/general.md b/docs/mapping/general.md new file mode 100644 index 0000000000..5cc4b691cc --- /dev/null +++ b/docs/mapping/general.md @@ -0,0 +1,54 @@ +# Type mapping + +The EF Core provider transparently maps the types supported by Npgsql at the ADO.NET level - see [the Npgsql ADO type mapping page](/doc/types/basic.html). + +This means that you can use PostgreSQL-specific types, such as `inet` or `circle`, directly in your entities. Simply define your properties just as if they were a simple type, such as a `string`: + +```c# +public class MyEntity +{ + public int Id { get; set; } + public string Name { get; set; } + public IPAddress IPAddress { get; set; } + public NpgsqlCircle Circle { get; set; } + public int[] SomeInts { get; set; } +} +``` + +Special types such as [arrays](array.md) and [enums](enum.md) have their own documentation pages with more details. + +[PostgreSQL composite types](https://www.postgresql.org/docs/current/static/rowtypes.html), while supported at the ADO.NET level, aren't yet supported in the EF Core provider. This is tracked by [#22](https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL/issues/22). + +# Explicitly specifying data types + +In some cases, your .NET property type can be mapped to several PostgreSQL data types; a good example is a `string`, which will be mapped to `text` by default, but can also be mapped to `jsonb`. You can explicitly specify the PostgreSQL data type by adding the following to your model's `OnModelCreating`: + +```c# +builder.Entity() + .Property(b => b.SomeStringProperty) + .HasColumnType("jsonb"); +``` + +Or, if you prefer annotations, use a `ColumnAttribute`: + +```c# +[Column(TypeName="jsonb")] +public string SomeStringProperty { get; set; } +``` + +## Operation translation to SQL + +Entity Framework Core allows providers to translate query expressions to SQL for database evaluation. For example, PostgreSQL supports [regular expression operations](http://www.postgresql.org/docs/current/static/functions-matching.html#FUNCTIONS-POSIX-REGEXP), and the Npgsql EF Core provider automatically translates .NET's `Regex.IsMatch()` to use this feature. Since evaluation happens at the server, table data doesn't need to be transferred to the client (saving bandwidth), and in some cases indexes can be used to speed things up. The same C# code on other providers will trigger client evaluation. + +Below are some Npgsql-specific translations, many additional standard ones are supported as well. See the other pages in the mapping section for more supported types and operations. + +| C# expression | SQL generated by Npgsql | +|------------------------------------------------------------|-------------------------| +| `.Where(c => Regex.IsMatch(c.Name, "^A+")` | [`WHERE "c"."Name" ~ '^A+'`](http://www.postgresql.org/docs/current/static/functions-matching.html#FUNCTIONS-POSIX-REGEXP) +| `.Where(c => EF.Functions.Like(c.Name, "foo%")` | [`WHERE "c"."Name" LIKE 'foo%'`](https://www.postgresql.org/docs/current/static/functions-matching.html#FUNCTIONS-LIKE) +| `.Where(c => EF.Functions.ILike(c.Name, "foo%")` | [`WHERE "c"."Name" ILIKE 'foo%'`](https://www.postgresql.org/docs/current/static/functions-matching.html#FUNCTIONS-LIKE) (case-insensitive LIKE) +| `.Select(c => EF.Functions.ToTsVector("english", c.Name))` | [`SELECT to_tsvector('english'::regconfig, "c"."Name")`](https://www.postgresql.org/docs/current/static/textsearch-controls.html#TEXTSEARCH-PARSING-DOCUMENTS) +| `.Select(c => EF.Functions.ToTsQuery("english", "pgsql"))` | [`SELECT to_tsquery('english'::regconfig, 'pgsql')`](https://www.postgresql.org/docs/current/static/textsearch-controls.html#TEXTSEARCH-PARSING-QUERIES) +| `.Where(c => c.SearchVector.Matches("Npgsql"))` | [`WHERE "c"."SearchVector" @@ 'Npgsql'`](https://www.postgresql.org/docs/current/static/textsearch-intro.html#TEXTSEARCH-MATCHING) +| `.Select(c => EF.Functions.ToTsQuery(c.SearchQuery).ToNegative())` | [`SELECT (!! to_tsquery("c"."SearchQuery"))`](https://www.postgresql.org/docs/current/static/textsearch-features.html#TEXTSEARCH-MANIPULATE-TSQUERY) +| `.Select(c => EF.Functions.ToTsVector(c.Name).SetWeight(NpgsqlTsVector.Lexeme.Weight.A))` | [`SELECT setweight(to_tsvector("c"."Name"), 'A')`](https://www.postgresql.org/docs/current/static/textsearch-features.html#TEXTSEARCH-MANIPULATE-TSVECTOR) diff --git a/docs/mapping/json.md b/docs/mapping/json.md new file mode 100644 index 0000000000..79d85f9971 --- /dev/null +++ b/docs/mapping/json.md @@ -0,0 +1,236 @@ +# JSON Mapping + +PostgreSQL has rich, built-in support for storing JSON columns and efficiently performing complex queries operations on them. Newcomers can read more about the PostgreSQL support on [the JSON types page](https://www.postgresql.org/docs/current/datatype-json.html), and on the [functions and operators page](https://www.postgresql.org/docs/current/functions-json.html). Note that the below mapping mechanisms support both the `jsonb` and `json` types, although the former is almost always preferred for efficiency reasons. + +The Npgsql EF Core provider allows you to map PostgreSQL JSON columns in three different ways: + +1. As simple strings +2. As strongly-typed user-defined types (POCOs) +3. As [System.Text.Json](https://devblogs.microsoft.com/dotnet/try-the-new-system-text-json-apis/) DOM types (JsonDocument or JsonElement) + +> [!NOTE] +> Mapping to POCO or to System.Text.Json types was introduced in version 3.0.0 + + +## String mapping + +The simplest form of mapping to JSON is via a regular string property, just like an ordinary text column: + +# [Data Annotations](#tab/data-annotations) + +```c# +public class SomeEntity +{ + public int Id { get; set; } + [Column(TypeName = "jsonb")] + public string Customer { get; set; } +} +``` + +# [Fluent API](#tab/fluent-api) + +```c# +class MyContext : DbContext +{ + public DbSet SomeEntities { get; set; } + + protected override void OnModelCreating(ModelBuilder modelBuilder) + { + modelBuilder.Entity() + .Property(b => b.Customer) + .HasColumnType("jsonb"); + } +} + +public class SomeEntity +{ + public int Id { get; set; } + public Customer Customer { get; set; } +} +``` + +*** + +With string mapping, the EF Core provider will save and load properties to database JSON columns, but will not do any further serialization or parsing - it's the developer's responsibility to handle the JSON contents, possibly using System.Text.Json to parse them. This mapping approach is more limited compared to the others. + +## POCO mapping + +If your column's JSON documents have a stable schema, you can map them to your own .NET types (or POCOs). The provider will use [the new System.Text.Json APIs](https://devblogs.microsoft.com/dotnet/try-the-new-system-text-json-apis/) under the hood to serialize instances to JSON documents before sending them to the database, and to deserialize documents coming from the database back. Just like EF Core can map a .NET type to rows in the table, this capability allows you to map a .NET type to a single JSON column. + +Mapping POCOs is extremely easy: simply add a property with your custom POCO type and instruct the provider to map it to JSON: + +# [Data Annotations](#tab/data-annotations) + +```c# +public class SomeEntity +{ + public int Id { get; set; } + [Column(TypeName = "jsonb")] + public Customer Customer { get; set; } +} + +public class Customer // Mapped to a JSON column in the table +{ + public string Name { get; set; } + public int Age { get; set; } + public Order[] Orders { get; set; } +} + +public class Order // Part of the JSON column +{ + public decimal Price { get; set; } + public string ShippingAddress { get; set; } +} +``` + +# [Fluent API](#tab/fluent-api) + +```c# +class MyContext : DbContext +{ + public DbSet SomeEntities { get; set; } + + protected override void OnModelCreating(ModelBuilder modelBuilder) + { + modelBuilder.Entity() + .Property(b => b.Customer) + .HasColumnType("jsonb"); + } +} + +public class SomeEntity // Mapped to a database table +{ + public int Id { get; set; } + public Customer Customer { get; set; } +} + +public class Customer // Mapped to a JSON column in the table +{ + public string Name { get; set; } + public int Age { get; set; } + public Order[] Orders { get; set; } +} + +public class Order // Part of the JSON column +{ + public decimal Price { get; set; } + public string ShippingAddress { get; set; } +} +``` + +*** + +You can now assign a regular `Customer` instance to the property, and once you call `SaveChanges()` it will be serialized to database, producing a document such as the following: + +```json +{ + "Age": 25, + "Name": "Joe", + "Orders": [ + {"Price": 9, "ShippingAddress": "Some address 1"}, + {"Price": 23, "ShippingAddress": "Some address 2"} + ] +} +``` + +Reading is just as simple: + +```c# +var someEntity = context.Entities.First(); +Console.WriteLine(someEntity.Customer.Orders[0].Price) +``` + +This provides a seamless mapping approach, and supports embedding nested types and arrays, resulting in complex JSON document schemas as shown above. This approach also allows you to traverse loaded JSON documents in a type-safe way, using regular C# syntax, and to use LINQ to query inside database JSON documents (see [Querying JSON columns](#querying-json-columns) below). + +## JsonDocument DOM mapping + +If your column JSON schema isn't stable, a strongly-typed POCO mapping may not be appropriate. The Npgsql provider also allows you to map the DOM document type provided by [System.Text.Json APIs](https://devblogs.microsoft.com/dotnet/try-the-new-system-text-json-apis/). + +```c# +public class SomeEntity +{ + public int Id { get; set; } + public JsonDocument Customer { get; set; } +} +``` + +Note that neither a data annotation nor the fluent API are required, as `JsonDocument` is automatically recognized and mapped to `jsonb`. + +Once a document is loaded from the database, you can traverse it: + +```c# +var someEntity = context.Entities.First(); +Console.WriteLine(someEntity.Customer.GetProperty("Orders")[0].GetProperty("Price").GetInt32()); +``` + +## Querying JSON columns + +Saving and loading documents these documents wouldn't be much use without the ability to query them. You can express your queries via the same LINQ constructs you are already using in EF Core: + +# [POCO Mapping](#tab/poco) + +```c# +var joes = context.CustomerEntries + .Where(e => e.Customer.Name == "Joe") + .ToList(); +``` + +# [JsonDocument Mapping](#tab/jsondocument) + +```c# +var joes = context.CustomerEntries + .Where(e => e.Customer.GetProperty("Name").GetString() == "Joe") + .ToList(); +``` + +*** + +The provider will recognize the traversal of a JSON document, and translate it to the correspond PostgreSQL JSON traversal operator, producing the following PostgreSQL-specific SQL: + +```sql +SELECT c.""Id"", c.""Customer"" +FROM ""CustomerEntries"" AS c +WHERE c.""Customer""->>'Name' = 'Joe' +``` + +[If indexes are set up properly](#indexing-json-columns), this can result in very efficient, server evaluation of searches with database JSON documents. + +The following expression types and functions are translated: + +# [POCO Mapping](#tab/poco) + +| C# expression | SQL generated by Npgsql | +|-------------------------------------------------------------------------------------------|------------------------------| +| `.Where(e => e.Customer.Name == "Joe")` | [`WHERE "Customer"->>'Name' = 'Joe'`](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-OP-TABLE) +| `.Where(e => e.Customer.Orders[1].Price = 8)` | [`WHERE "Customer"#>>'{Orders,0,Price}'[1] = 8`](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-OP-TABLE) +| `.Where(e => e.Customer.Orders.Length == 2)` | [`WHERE jsonb_array_length("Customer"->'Orders' = 2`](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-PROCESSING-TABLE) +| `.Where(e => EF.Functions.JsonContains(e.Customer, @"{""Name"": ""Joe"", ""Age"": 25}")` | [`WHERE "Customer" @> '{"Name": "Joe", "Age": 25}'`](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) +| `.Where(e => EF.Functions.JsonContained(@"{""Name"": ""Joe"", ""Age"": 25}", e.Customer)` | [`WHERE '{"Name": "Joe", "Age": 25}' <@ "Customer"`](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) +| `.Where(e => EF.Functions.JsonExists(e.Customer, "Age")` | [`WHERE "Customer" ? 'Age'`](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) +| `.Where(e => EF.Functions.JsonExistsAny(e.Customer, "Age", "Address")` | [`WHERE "Customer" ?\| ARRAY['Age','Address']`](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) +| `.Where(e => EF.Functions.JsonExistsAll(e.Customer, "Age", "Address")` | [`WHERE "Customer" ?& ARRAY['Age','Address']`](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) +| `.Where(e => EF.Functions.JsonTypeof(e.Customer.Age)` | [`WHERE jsonb_typeof("Customer"->'Age')`](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-PROCESSING-TABLE) + +# [JsonDocument Mapping](#tab/jsondocument) + +| C# expression | SQL generated by Npgsql | +|-------------------------------------------------------------------------------------------|------------------------------| +| `.Where(e => e.Customer.GetProperty("Name").GetString() == "Joe")` | [`WHERE "Customer"->>'Name' = 'Joe'`](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-OP-TABLE) +| `.Where(e => e.Customer.GetProperty("Orders")[1].GetProperty("Price").GetInt32() = 8)` | [`WHERE "Customer"#>>'{Orders,0,Price}'[1] = 8`](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-OP-TABLE) +| `.Where(e => e.Customer.GetProperty("Orders").GetArrayLength() == 2)` | [`WHERE jsonb_array_length("Customer"->'Orders' = 2`](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-PROCESSING-TABLE) +| `.Where(e => EF.Functions.JsonContains(e.Customer, @"{""Name"": ""Joe"", ""Age"": 25}")` | [`WHERE "Customer" @> '{"Name": "Joe", "Age": 25}'`](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) +| `.Where(e => EF.Functions.JsonContained(@"{""Name"": ""Joe"", ""Age"": 25}", e.Customer)` | [`WHERE '{"Name": "Joe", "Age": 25}' <@ "Customer"`](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) +| `.Where(e => EF.Functions.JsonExists(e.Customer, "Age")` | [`WHERE "Customer" ? 'Age'`](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) +| `.Where(e => EF.Functions.JsonExistsAny(e.Customer, "Age", "Address")` | [`WHERE "Customer" ?\| ARRAY['Age','Address']`](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) +| `.Where(e => EF.Functions.JsonExistsAll(e.Customer, "Age", "Address")` | [`WHERE "Customer" ?& ARRAY['Age','Address']`](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) +| `.Where(e => EF.Functions.JsonTypeof(e.Customer.GetProperty("Age"))` | [`WHERE jsonb_typeof("Customer"->'Age')`](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-PROCESSING-TABLE) + +*** + +## Indexing JSON columns + +> [!NOTE] +> A section on indices will be added. In the meantime consult the PostgreSQL documentation and other guides on the Internet. + +These are early days for EF Core JSON support, and you'll likely run into some limitations. Please let us know how the current features are working for you and what you'd like to see. + diff --git a/docs/mapping/nodatime.md b/docs/mapping/nodatime.md new file mode 100644 index 0000000000..3c2c1fb520 --- /dev/null +++ b/docs/mapping/nodatime.md @@ -0,0 +1,50 @@ +# Date/Time Mapping with NodaTime + +# What is NodaTime? + +By default, [the PostgreSQL date/time types](https://www.postgresql.org/docs/current/static/datatype-datetime.html) are mapped to the built-in .NET types (`DateTime`, `TimeSpan`). Unfortunately, these built-in types are flawed in many ways. The [NodaTime library](http://nodatime.org/) was created to solve many of these problems, and if your application handles dates and times in anything but the most basic way, you should consider using it. To learn more [read this blog post by Jon Skeet](http://blog.nodatime.org/2011/08/what-wrong-with-datetime-anyway.html). + +Beyond NodaTime's general advantages, some specific advantages NodaTime for PostgreSQL date/time mapping include: + +* NodaTime defines some types which are missing from the BCL, such as `LocalDate`, `LocalTime`, and `OffsetTime`. These cleanly correspond to PostgreSQL `date`, `time` and `timetz`. +* `Period` is much more suitable for mapping PostgreSQL `interval` than `TimeSpan`. +* NodaTime types can fully represent PostgreSQL's microsecond precision, and can represent dates outside the BCL's date limit (1AD-9999AD). + +# Setup + +To set up the NodaTime plugin, add the [Npgsql.EntityFrameworkCore.PostgreSQL.NodaTime nuget](https://www.nuget.org/packages/Npgsql.EntityFrameworkCore.PostgreSQL.NodaTime) to your project. Then, make the following modification to your `UseNpgsql()` line: + +```c# +protected override void OnConfiguring(DbContextOptionsBuilder builder) +{ + builder.UseNpgsql("Host=localhost;Database=test;Username=npgsql_tests;Password=npgsql_tests", + o => o.UseNodaTime()); +} +``` + +This will set up all the necessary mappings and operation translators. You can now use NodaTime types as regular properties in your entities, and even perform some operations: + +```c# +public class Post +{ + public int Id { get; set; } + public string Name { get; set; } + public Instant CreationTime { get; set; } +} + +var recentPosts = context.Posts.Where(p => p.CreationTime > someInstant); +``` + +## Member translation + +Currently, the EF Core provider knows how to translate the most date/time component members of NodaTime's `LocalDateTime`, `LocalDate`, `LocalTime` and `Period`. In other words, the following query will be translated to SQL and evaluated server-side: + +```c# +// Get all events which occurred on a Monday +var mondayEvents = context.Events.Where(p => p.SomeDate.DayOfWeek == DayOfWeek.Monday); + +// Get all events which occurred before the year 2000 +var oldEvents = context.Events.Where(p => p.SomeDate.Year < 2000); +``` + +Note that the plugin is far from covering all translations. If a translation you need is missing, please open an issue to request for it. diff --git a/docs/mapping/nts.md b/docs/mapping/nts.md new file mode 100644 index 0000000000..498aa9a847 --- /dev/null +++ b/docs/mapping/nts.md @@ -0,0 +1,124 @@ +## Spatial Mapping with NetTopologySuite + +> [!NOTE] +> It's recommended that you start by reading the general [Entity Framework Core docs on spatial support](https://docs.microsoft.com/ef/core/modeling/spatial). + +PostgreSQL supports spatial data and operations via [the PostGIS extension](https://postgis.net/), which is a mature and feature-rich database spatial implementation. .NET doesn't provide a standard spatial library, but [NetTopologySuite](https://github.com/NetTopologySuite/NetTopologySuite) is quite a good candidate. The Npgsql EF Core provider has a plugin which allows you to map NetTopologySuite's types PostGIS columns, and even translate many useful spatial operations to SQL. This is the recommended way to interact with spatial types in Npgsql. + +Note that the EF Core NetTopologySuite plugin depends on [the Npgsql ADO.NET NetTopology plugin](http://www.npgsql.org/doc/types/nts.html), which provides NetTopologySuite support at the lower level. The EF Core plugin automatically arranged for the ADO.NET plugin to be set up. + +# Setup + +To set up the NetTopologySuite plugin, add the [Npgsql.EntityFrameworkCore.PostgreSQL.NetTopologySuite nuget](https://www.nuget.org/packages/Npgsql.EntityFrameworkCore.PostgreSQL.NetTopologySuite) to your project. Then, make the following modification to your `UseNpgsql()` line: + +```c# +protected override void OnConfiguring(DbContextOptionsBuilder builder) +{ + builder.UseNpgsql("Host=localhost;Database=test;Username=npgsql_tests;Password=npgsql_tests", + o => o.UseNetTopologySuite()); +} +``` + +This will set up all the necessary mappings and operation translators. In addition, to make sure that the PostGIS extension is installed in your database, add the following to your DbContext: + +```c# +protected override void OnModelCreating(ModelBuilder builder) +{ + builder.HasPostgresExtension("postgis"); +} +``` + +At this point spatial support is set up. You can now use NetTopologySuite types as regular properties in your entities, and even perform some operations: + +```c# +public class City +{ + public int Id { get; set; } + public string Name { get; set; } + public Point Location { get; set; } +} + +var nearbyCities = context.Cities.Where(c => c.Location.Distance(somePoint) < 100); +``` + +## Constraining your type names + +With the code above, the provider will create a database column of type `geometry`. This is perfectly fine, but be aware that this type accepts any geometry type (point, polygon...), with any coordinate system (XY, XYZ...). It's good practice to constrain the column to the exact type of data you will be storing, but unfortunately the provider isn't aware of your required coordinate system and therefore can't do that for you. Consider explicitly specifying your column types on your properties as follows: + +```c# +[Column(TypeName="geometry (point)")] +public Point Location { get; set; } +``` + +This will constrain your column to XY points only. The same can be done via the fluent API with `HasColumnType()`. + +## Operation translation + +The following table lists NetTopologySuite operations which are translated to PostGIS SQL operations. This allows you to use these NetTopologySuite methods and members efficiently - evaluation will happen on the server side. Since evaluation happens at the server, table data doesn't need to be transferred to the client (saving bandwidth), and in some cases indexes can be used to speed things up. + +Note that the plugin is far from covering all spatial operations. If an operation you need is missing, please open an issue to request for it. + +| This C# expression... | ... gets translated to this SQL | +|----------------------------------------------------------|---------------------------------| +| .Where(c => c.Polygon.Area() > x) | [WHERE ST_Area(c."Polygon") > x](https://postgis.net/docs/manual-2.4/ST_Area.html) +| .Where(c => c.Polygon.AsText() = x | [WHERE ST_AsText(c."Polygon") = x](https://postgis.net/docs/manual-2.4/ST_AsText.html) +| .Where(c => c.Polygon.Boundary = x | [WHERE ST_AsCoundary(c."Polygon") = x](https://postgis.net/docs/manual-2.4/ST_Boundary.html) +| .Where(c => c.Polygon.Contains(x)) | [WHERE ST_Contains(c."Polygon", x)](https://postgis.net/docs/manual-2.4/ST_Contains.html) +| .Where(c => c.Polygon.Covers(x)) | [WHERE ST_Covers(c."Polygon", x)](https://postgis.net/docs/manual-2.4/ST_Covers.html) +| .Where(c => c.Polygon.CoveredBy(x)) | [WHERE ST_CoveredBy(c."Polygon", x)](https://postgis.net/docs/manual-2.4/ST_CoveredBy.html) +| .Where(c => c.Polygon.Crosses(x)) | [WHERE ST_Crosses(c."Polygon", x)](https://postgis.net/docs/manual-2.4/ST_Crosses.html) +| .Where(c => c.Polygon.Difference(x) = y) | [WHERE ST_Difference(c."Polygon", x) = y](https://postgis.net/docs/manual-2.4/ST_Difference.html) +| .Where(c => c.Polygon.Disjoint(x)) | [WHERE ST_Disjoint(c."Polygon", x)](https://postgis.net/docs/manual-2.4/ST_Disjoint.html) +| .Where(c => c.Point.Distance(x) > y) | [WHERE ST_Distance(c."Polygon", x) > y](https://postgis.net/docs/manual-2.4/ST_Distance.html) +| .Where(c => c.Polygon.Equals(x)) | [WHERE c."Polygon" = x](https://postgis.net/docs/manual-2.4/ST_Geometry_EQ.html) +| .Where(c => c.Polygon.EqualsExact(x)) | [WHERE c."Polygon" = x](https://postgis.net/docs/manual-2.4/ST_Geometry_EQ.html) +| .Where(c => c.Polygon.EqualsTopologically(x)) | [WHERE ST_Equals(c."Polygon", x)](https://postgis.net/docs/manual-2.4/ST_Equals.html) +| .Where(c => c.Geometry.GeometryType() = x) | [WHERE GeometryType(c."GeomCollection") = x](https://postgis.net/docs/manual-2.4/GeometryType.html) +| .Where(c => c.GeomCollection.GetGeometryN(2) = x) | [WHERE ST_GeometryN(c."GeomCollection", 3) = x](https://postgis.net/docs/manual-2.4/ST_GeometryN.html) +| .Where(c => c.Polygon.Intersection(x) = y) | [WHERE ST_Intersection(c."Polygon", x) = y](https://postgis.net/docs/manual-2.4/ST_Intersection.html) +| .Where(c => c.Polygon.Intersects(x)) | [WHERE ST_Intersects(c."Polygon", x)](https://postgis.net/docs/manual-2.4/ST_Intersects.html) +| .Where(c => c.LineString.IsClosed()) | [WHERE ST_IsClosed(c."LineString")](https://postgis.net/docs/manual-2.4/ST_IsClosed.html) +| .Where(c => c.GeomCollection.IsEmpty()) | [WHERE ST_IsEmpty(c."GeomCollection")](https://postgis.net/docs/manual-2.4/ST_IsEmpty.html) +| .Where(c => c.Polygon.IsSimple()) | [WHERE ST_IsSimple(c."Polygon")](https://postgis.net/docs/manual-2.4/ST_IsSimple.html) +| .Where(c => c.Polygon.IsValid()) | [WHERE ST_IsValid(c."Polygon")](https://postgis.net/docs/manual-2.4/ST_IsValid.html) +| .Where(c => c.LineString.Length > x) | [WHERE ST_Length(c."LineString") > x](https://postgis.net/docs/manual-2.4/ST_Length.html) +| .Where(c => c.GeomCollection.NumGeometries > x) | [WHERE ST_NumGeometries(c."GeomCollection") > x](https://postgis.net/docs/manual-2.4/ST_NumGeometries.html) +| .Where(c => c.LineString.NumPoints > x) | [WHERE ST_NumPoints(c."LineString") > x](https://postgis.net/docs/manual-2.4/ST_NumPoints.html) +| .Where(c => c.Polygon.Overlaps(x)) | [WHERE ST_Overlaps(c."Polygon", x)](https://postgis.net/docs/manual-2.4/ST_Overlaps.html) +| .Where(c => c.Polygon.Relate(x) == y) | [WHERE ST_Relate(c."Polygon", x) = y](https://postgis.net/docs/manual-2.4/ST_Relate.html) +| .Where(c => c.LineString.Reverse() == x) | [WHERE ST_Reverse(c."Polygon") = x](https://postgis.net/docs/manual-2.4/ST_Reverse.html) +| .Where(c => c.Polygon.SymmetricDifference(x) == y) | [WHERE ST_SymDifference(c."Polygon", x) = y](https://postgis.net/docs/manual-2.4/ST_SymDifference.html) +| .Where(c => c.Polygon.Touches(x)) | [WHERE ST_Touches(c."Polygon", x)](https://postgis.net/docs/manual-2.4/ST_Touches.html) +| .Where(c => c.Polygon.ToText() = x) | [WHERE ST_AsText(c."Polygon") = x](https://postgis.net/docs/manual-2.4/ST_AsText.html) +| .Where(c => c.Polygon.Union(x) = y) | [WHERE ST_Union(c."Polygon", x) = y](https://postgis.net/docs/manual-2.4/ST_Union.html) +| .Where(c => c.Polygon.Within(x)) | [WHERE ST_Within(c."Polygon", x)](https://postgis.net/docs/manual-2.4/ST_Within.html) +| .Where(c => c.Point.X == 3) | [WHERE ST_X(c."Point") = 3](https://postgis.net/docs/manual-2.4/ST_X.html) +| .Where(c => c.Point.Y == 3) | [WHERE ST_Y(c."Point") = 3](https://postgis.net/docs/manual-2.4/ST_Y.html) +| .Where(c => c.Point.Z == 3) | [WHERE ST_Z(c."Point") = 3](https://postgis.net/docs/manual-2.4/ST_Z.html) + +## Geography (geodetic) support + +PostGIS has two types: `geometry` (for Cartesian coordinates) and `geography` (for geodetic or spherical coordinates). You can read about the geometry/geography distinction [in the PostGIS docs](https://postgis.net/docs/manual-2.4/using_postgis_dbmanagement.html#PostGIS_Geography) or in [this blog post](http://workshops.boundlessgeo.com/postgis-intro/geography.html). In a nutshell, `geography` is much more accurate when doing calculations over long distances, but is more expensive computationally and supports only a small subset of the spatial operations supported by `geometry`. + +The Npgsql provider will be default map all NetTopologySuite types to PostGIS `geometry`. However, you can instruct it to map certain properties to `geography` instead: + +```c# +protected override void OnModelCreating(ModelBuilder builder) +{ + builder.Entity().Property(b => b.Location).HasColumnType("geography (point)"); +} +``` + +or via an attribute: + +```c# +public class City +{ + public int Id { get; set; } + public string Name { get; set; } + [Column(TypeName="geography")] + public Point Location { get; set; } +} +``` + +Once you do this, your column will be created as `geography`, and spatial operations will behave as expected. diff --git a/docs/mapping/range.md b/docs/mapping/range.md new file mode 100644 index 0000000000..3bec36b78e --- /dev/null +++ b/docs/mapping/range.md @@ -0,0 +1,74 @@ +# Range Type Mapping + +PostgreSQL has the unique feature of supporting [*range data types*](https://www.postgresql.org/docs/current/static/rangetypes.html). Ranges represent a range of numbers, dates or other data types, and allow you to easily query ranges which contain a value, perform set operations (e.g. query ranges which contain other ranges), and other similar operations. The range operations supported by PostgreSQL are listed [in this page](https://www.postgresql.org/docs/current/static/functions-range.html). The Npgsql EF Core provider allows you to seemlessly map PostgreSQL ranges, and even perform operations on them that get translated to SQL for server evaluation. + +# Mapping ranges + +Npgsql maps PostgreSQL ranges to the generic CLR type `NpgqslRange`: + +```c# +public class Event +{ + public int Id { get; set; } + public string Name { get; set; } + public NpgsqlRange Duration { get; set; } +} +``` + +This will create a column of type `daterange` in your database. You can similarly have properties of type `NpgsqlRange`, `NpgsqlRange`, etc. + +# User-defined ranges + +> [!NOTE] +> This feature was introduced in version 2.2 + +PostgreSQL comes with 6 built-in ranges: `int4range`, `int8range`, `numrange`, `tsrange`, `tstzrange`, `daterange`; these can be used simply by adding the appropriate `NpgsqlRange` property in your entities as shown above. You can also define your own range types over arbitrary types, and use those in EF Core as well. + +To make the EF Core type mapper aware of your user-defined range, call the `MapRange()` method in your context's `OnConfiguring()` method as follows: +```c# +protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) + => optionsBuilder.UseNpgsql( + "", + options => options.MapRange("floatrange")); +``` + +This allows you to have properties of type `NpgsqlRange`, which will be mapped to PostgreSQL `floatrange`. + +The above does *not* create the `floatrange` type for you. In order to do that, include the following in your context's `OnModelCreating()`: + +```c# +protected override void OnModelCreating(ModelBuilder modelBuilder) + => modelBuilder.ForNpgsqlHasRange("floatrange", "real"); +``` + +This will cause the appropriate [`CREATE TYPE ... AS RANGE`](https://www.postgresql.org/docs/current/static/sql-createtype.html) statement to be generated in your migrations, ensuring that your range is created and ready for use. Note that `ForNpgsqlHasRange()` supports additional parameters as supported by PostgreSQL `CREATE TYPE`. + +# Operation translation + +Ranges can be queried via extensions methods on `NpgsqlRange`: + +```c# +var events = context.Events.Where(p => p.Duration.Contains(someDate)); +``` + +This will translate to an SQL operation using the PostgreSQL `@>` operator, evaluating at the server and saving you from transfering the entire `Events` table to the client. Note that you can (and probably should) create indexes to make this operation more efficient, see the PostgreSQL docs for more info. + +The following table lists the range operations that currently get translated. If you run into a missing operation, please open an issue. + +| C# expression | SQL generated by Npgsql | +|------------------------------------------------------------|-------------------------| +| `.Where(c => c.SomeRange.Contains(3))` | [`WHERE x."SomeRange" @> 3`](https://www.postgresql.org/docs/current/static/functions-range.html#RANGE-OPERATORS-TABLE) +| `.Where(c => c.SomeRange.Contains(otherRange))` | [`WHERE x."SomeRange" @> @__otherRange_0`](https://www.postgresql.org/docs/current/static/functions-range.html#RANGE-OPERATORS-TABLE) +| `.Where(c => c.SomeRange.ContainedBy(otherRange))` | [`WHERE x."SomeRange" <@ @__otherRange_0`](https://www.postgresql.org/docs/current/static/functions-range.html#RANGE-OPERATORS-TABLE) +| `.Where(c => c.SomeRange == otherRange)` | [`WHERE x."SomeRange" = @__otherRange_0`](https://www.postgresql.org/docs/current/static/functions-range.html#RANGE-OPERATORS-TABLE) +| `.Where(c => c.SomeRange != otherRange)` | [`WHERE x."SomeRange" <> @__otherRange_0`](https://www.postgresql.org/docs/current/static/functions-range.html#RANGE-OPERATORS-TABLE) +| `.Where(c => c.SomeRange.Overlaps(otherRange))` | [`WHERE x."SomeRange" && @__otherRange_0`](https://www.postgresql.org/docs/current/static/functions-range.html#RANGE-OPERATORS-TABLE) +| `.Where(c => c.SomeRange.IsStrictlyLeftOf(otherRange))` | [`WHERE x."SomeRange" << @__otherRange_0`](https://www.postgresql.org/docs/current/static/functions-range.html#RANGE-OPERATORS-TABLE) +| `.Where(c => c.SomeRange.IsStrictlyRightOf(otherRange))` | [`WHERE x."SomeRange" >> @__otherRange_0`](https://www.postgresql.org/docs/current/static/functions-range.html#RANGE-OPERATORS-TABLE) +| `.Where(c => c.SomeRange.DoesNotExtendLeftOf(otherRange))` | [`WHERE x."SomeRange" &> @__otherRange_0`](https://www.postgresql.org/docs/current/static/functions-range.html#RANGE-OPERATORS-TABLE) +| `.Where(c => c.SomeRange.DoesNotExtendRightOf(otherRange))`| [`WHERE x."SomeRange" <& @__otherRange_0`](https://www.postgresql.org/docs/current/static/functions-range.html#RANGE-OPERATORS-TABLE) +| `.Where(c => c.SomeRange.IsAdjacentTo(otherRange))` | [`WHERE x."SomeRange" -\|- @__otherRange_0`](https://www.postgresql.org/docs/current/static/functions-range.html#RANGE-OPERATORS-TABLE) +| `.Select(c => c.SomeRange.Union(otherRange))` | [`SELECT x."SomeRange" + @__otherRange_0`](https://www.postgresql.org/docs/current/static/functions-range.html#RANGE-OPERATORS-TABLE) +| `.Select(c => c.SomeRange.Intersect(otherRange))` | [`SELECT x."SomeRange" * @__otherRange_0`](https://www.postgresql.org/docs/current/static/functions-range.html#RANGE-OPERATORS-TABLE) +| `.Select(c => c.SomeRange.Except(otherRange))` | [`SELECT x."SomeRange" - @__otherRange_0`](https://www.postgresql.org/docs/current/static/functions-range.html#RANGE-OPERATORS-TABLE) + diff --git a/docs/miscellaneous.md b/docs/miscellaneous.md new file mode 100644 index 0000000000..6e60475be6 --- /dev/null +++ b/docs/miscellaneous.md @@ -0,0 +1,118 @@ +# Miscellaneous + +## PostgreSQL extensions + +The Npgsql EF Core provider allows you to specify PostgreSQL extensions that should be set up in your database. +Simply use `HasPostgresExtension` in your context's `OnModelCreating` method: + +```c# +protected override void OnModelCreating(ModelBuilder modelBuilder) + => modelBuilder.HasPostgresExtension("hstore"); +``` + +## Optimistic Concurrency and Concurrency Tokens + +Entity Framework Core supports the concept of optimistic concurrency - a property on your entity is designated as a concurrency token, and EF Core detects concurrent modifications by checking whether that token has changed since the entity was read. You can read more about this in the [EF Core docs](https://docs.microsoft.com/ef/core/modeling/concurrency). + +Although applications can update concurrency tokens themselves, we frequently rely on the database automatically updating a column on update - a "last modified" timestamp, an SQL Server `rowversion`, etc. Unfortunately PostgreSQL doesn't have such auto-updating columns - but there is one feature that can be used for concurrency token. All PostgreSQL tables have a set of [implicit and hidden system columns](https://www.postgresql.org/docs/current/static/ddl-system-columns.htm://www.postgresql.org/docs/current/static/ddl-system-columns.html), among which `xmin` holds the ID of the latest updating transaction. Since this value automatically gets updated every time the row is changed, it is ideal for use as a concurrency token. + +To enable this feature on an entity, insert the following code into your context's `OnModelCreating` method: + +```c# +protected override void OnModelCreating(ModelBuilder modelBuilder) + => modelBuilder.Entity() + .ForNpgsqlUseXminAsConcurrencyToken(); +``` + +## Execution Strategy + +Since 2.0.0, the Npgsql EF Core provider provides a retrying execution strategy, which will attempt to detect most transient PostgreSQL/network errors and will automatically retry your operation. To enable, place the following code in your context's `OnModelConfiguring`: + +```c# +protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) + => optionsBuilder.UseNpgsql( + "", + options => options.EnableRetryOnFailure()); +``` + +This strategy relies on the `IsTransient` property of `NpgsqlException`. Both this property and the retrying strategy are new and should be considered somewhat experimental - please report any issues. + +## Comments + +PostgreSQL allows you to [attach comments](https://www.postgresql.org/docs/current/static/sql-syntax-lexical.html#SQL-SYNTAX-COMMENTS) to database objects, which can help explain their purpose for someone examining the schema. The Npgsql EF Core provider supports this for tables or columns, simply set the comment in your model's `OnModelCreating` as follows: + +```c# +protected override void OnModelCreating(ModelBuilder modelBuilder) + => modelBuilder.Entity() + .ForNpgsqlHasComment("Some comment"); +``` + +## Certificate authentication + +The Npgsql allows you to provide a callback for verifying the server-provided certificates, and to provide a callback for providing certificates to the server. The latter, if properly set up on the PostgreSQL side, allows you to do client certificate authentication - see [the Npgsql docs](http://www.npgsql.org/doc/security.html#encryption-ssltls) and also [the PostgreSQL docs](https://www.postgresql.org/docs/current/static/ssl-tcp.html#SSL-CLIENT-CERTIFICATES) on setting this up. + +The Npgsql EF Core provider allows you to set these two callbacks on the `DbContextOptionsBuilder` as follows: + +```c# +protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) + => optionsBuilder.UseNpgsql( + "", + options => + { + options.RemoteCertificateValidationCallback(MyCallback1); + options.ProvideClientCertificatesCallback(MyCallback2); + }); +``` + +You may also consider passing `Trust Server Certificate=true` in your connection string to make Npgsql accept whatever certificate your PostgreSQL provides (useful for self-signed certificates). + +## Database Creation + +### Specifying the administrative db + +When the Npgsql EF Core provider creates or deletes a database (`EnsureCreated()`, `EnsureDeleted()`), it must connect to an administrative database which already exists (with PostgreSQL you always have to be connected to some database, even when creating/deleting another database). Up to now the `postgres` database was used, which is supposed to always be present. + +However, there are some PostgreSQL-like databases where the `postgres` database is not available. For these cases you can specify the administrative database as follows: + +```c# +protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) + => optionsBuilder.UseNpgsql( + "", + options => options.UseAdminDatabase("my_admin_db")); +``` + +### Using a database template + +When creating a new database, +[PostgreSQL allows specifying another "template database"](http://www.postgresql.org/docs/current/static/manage-ag-templatedbs.html) +which will be copied as the basis for the new one. This can be useful for including database entities which are not managed by Entity Framework Core. You can trigger this by using `HasDatabaseTemplate` in your context's `OnModelCreating`: + +```c# +protected override void OnModelCreating(ModelBuilder modelBuilder) + => modelBuilder.HasDatabaseTemplate("my_template_db"); +``` + +### Setting a tablespace + +PostgreSQL allows you to locate your database in different parts of your filesystem, [via tablespaces](https://www.postgresql.org/docs/current/static/manage-ag-tablespaces.html). The Npgsql EF Core provider allows you to specify your database's namespace: + +```c# +protected override void OnModelCreating(ModelBuilder modelBuilder) + => modelBuilder.ForNpgsqlUseTablespace("my_tablespace"); +``` + +You must have created your tablespace prior to this via the `CREATE TABLESPACE` command - the Npgsql EF Core provider does not do this for you. Note also that specifying a tablespace on specific tables is not supported. + +## CockroachDB Interleave In Parent + +If you're using CockroachDB, the Npgsql EF Core provider exposes its ["interleave in parent" feature](https://www.cockroachlabs.com/docs/stable/interleave-in-parent.html). Use the following code: + +```c# +protected override void OnModelCreating(ModelBuilder modelBuilder) + => modelBuilder.Entity() + .ForCockroachDbInterleaveInParent( + typeof(ParentEntityType), + new List { "prefix_column_1", "prefix_column_2" }); +``` + + diff --git a/docs/modeling/generated-properties.md b/docs/modeling/generated-properties.md new file mode 100644 index 0000000000..875b1653ae --- /dev/null +++ b/docs/modeling/generated-properties.md @@ -0,0 +1,116 @@ +# Value Generation + +> [!CAUTION] +> In 3.0.0, the default value generation strategy has changed from the older SERIAL columns to the newer IDENTITY columns. Read the below carefully if you are migrating an existing database. + +> [!NOTE] +> It's recommended that you start by reading the general [Entity Framework Core docs on generated properties](https://docs.microsoft.com/en-us/ef/core/modeling/generated-properties). + +## Serial and identity columns (auto-increment) + +### Introduction + +Since PostgreSQL 10, the standard way to define auto-incrementing columns is "identity columns". Prior to version 10, "serial columns" were used, which are less SQL-compliant and generally more difficult to manage. For more information on these, [see this blog post](https://blog.2ndquadrant.com/postgresql-10-identity-columns/). Note that since PostgreSQL 10, both support `smallint`, `integer` and `bigint` as their data type. + +The Npgsql EF Core provider allows you to choose which of the above you want on a property-by-property basis, or globally on your model. The following "value generation strategies" are available: + +* *Identity by default*: an identity column whose values are *by default* generated at the database, but you can still override this behavior by providing values from your application. This will generate the clause `GENERATED BY DEFAULT AS IDENTITY` on your column, and is the default value generation strategy. +* *Identity always*: an identity column whose values are *always* generated at the database - you cannot provide values from your application. This will generate the clause `GENERATED ALWAYS AS IDENTITY` on your column. +* *Serial*: the traditional PostgreSQL serial column. This will create the column with the `serial` datatype. Recommended only if you are using an older PostgreSQL version. +* *Sequence HiLo*: See below + +Prior to version 3.0, the Npgsql provider generates "serial" columns for ID columns; starting with version 3.0, it generates "identity by default" instead. In other words, when `ValueGeneratedOnAdd` is specified on a `short`, `int` or `long` property, the Npgsql provider will automatically map it to a serial or identity column. Note that EF Core will automatically recognize key properties by convention (e.g. a property called `Id` in your entity) and will implicitly set them to `ValueGeneratedOnAdd`; a standard model with ID columns should automatically get created with the appropriate column type. + +> [!CAUTION] +> Since the default strategy has changed, if you have an existing database with migrations, the the first migration created after upgrading to version 3.0 will alter your tables and convert serial columns to identity ones. This is a sensitive, one-time migration operation that should be done with care, and carefully tested before deployment to production. Changing a value generation is a significant change to an existing database. + +You can easily control the value generation strategy for the entire model. For example, to opt out of the change to identity columns, simply place the following in your context's `OnModelCreating()`: + +```c# +protected override void OnModelCreating(ModelBuilder modelBuilder) + => modelBuilder.UseSerialColumns(); +``` + +Note that if you are using PostgreSQL 9.6 or older, identity columns will not work. It is recommended to place the provider in compatibility mode with your specific version - this will also affect the default value generation strategy: + +```c# +protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) + => optionsBuilder.UseNpgsql("...", o => o.SetPostgresVersion(9, 6)); +``` + +## Standard sequence-driven columns + +While `serial` sets up a sequence for you, you may want to manage sequence creation yourself. This can be useful for cases where you need to control the sequence's increment value (i.e. increment by 2), populate two columns from the same sequence, etc. Adding a sequence to your model is described in [the general EF Core documentation](https://docs.microsoft.com/ef/core/modeling/relational/sequences); once the sequence is specified, you can simply set a column's default value to extract the next value from that sequence. Note that the SQL used to fetch the next value from a sequence differs across databases (see [the PostgreSQL docs](https://www.postgresql.org/docs/current/static/functions-sequence.html)). Your models' `OnModelCreating` should look like this: + +```c# +protected override void OnModelCreating(ModelBuilder modelBuilder) +{ + modelBuilder.HasSequence("OrderNumbers") + .StartsAt(1000) + .IncrementsBy(5); + + modelBuilder.Entity() + .Property(o => o.OrderNo) + .HasDefaultValueSql("nextval('\"OrderNumbers\"')"); +} +``` + +## HiLo Autoincrement Generation + +One disadvantage of database-generated values is that these values must be read back from the database after a row is inserted. If you're saving multiple related entities, this means you must perform multiple roundtrips as the first entity's generated key must be read before writing the second one. One solution to this problem is HiLo value generation: rather than relying on the database to generate each and every value, the application "allocates" a range of values, which it can then populate directly on new entities without any additional roundtrips. When the range is exhausted, a new range is allocated. In practical terms, this uses a sequence that increments by some large value (100 by default), allowing the application to insert 100 rows autonomously. + +To use HiLo, specify `ForNpgsqlUseSequenceHiLo` on a property in your model's `OnModelCreating`: + +```c# +protected override void OnModelCreating(ModelBuilder modelBuilder) + => modelBuilder.Entity() + .Property(b => b.Id) + .ForNpgsqlUseSequenceHiLo(); +``` + +You can also make your model use HiLo everywhere: + +```c# +protected override void OnModelCreating(ModelBuilder modelBuilder) + => modelBuilder.ForNpgsqlUseSequenceHiLo(); +``` + +## Guid/UUID Generation + +By default, if you specify `ValueGeneratedOnAdd` on a Guid property, a random Guid value will be generated client-side and sent to the database. + +If you prefer to generate values in the database instead, you can do so by specifying `HasDefaultValueSql` on your property. Note that PostgreSQL doesn't include any Guid/UUID generation functions, you must add an extension such as `uuid-ossp` or `pgcrypto`. This can be done by placing the following code in your model's `OnModelCreating`: + +```c# +protected override void OnModelCreating(ModelBuilder modelBuilder) + => modelBuilder.HasPostgresExtension("uuid-ossp") + .Entity() + .Property(e => e.SomeGuidProperty) + .HasDefaultValueSql("uuid_generate_v4()"); +``` + +See [the PostgreSQL docs on UUID for more details](https://www.postgresql.org/docs/current/static/datatype-uuid.html). + +## Computed Columns (On Add or Update) + +> [!NOTE] +> This feature was introduced in 3.0.0. + +The upcoming PostgreSQL 12 is adding support for [stored generated columns](https://www.postgresql.org/docs/12/ddl-generated-columns.html), and Npgsql feature supports that feature as well. The following configuration: + +```c# +protected override void OnModelCreating(ModelBuilder modelBuilder) +{ + modelBuilder.Entity() + .Property(p => p.DisplayName) + .HasComputedColumnSql(@"""FirstName"" || ' ' || ""LastName"""); +} +``` + +Will cause the following migration SQL to be generated + +```sql +ALTER TABLE ""Person"" ADD ""DisplayName"" text GENERATED ALWAYS AS (""FirstName"" || ' ' || ""LastName"") STORED; +``` + +Note that this is a *stored* column - it is computed once when the row is updated, and takes space on disk. Virtual computed columns, which are computed on each select, are not yet supported by PostgreSQL. \ No newline at end of file diff --git a/docs/modeling/indexes.md b/docs/modeling/indexes.md new file mode 100644 index 0000000000..9a869b7b7d --- /dev/null +++ b/docs/modeling/indexes.md @@ -0,0 +1,49 @@ +# Indexes + +PostgreSQL and the Npgsql provider support the standard index modeling described in [the EF Core docs](https://docs.microsoft.com/ef/core/modeling/indexes). This page describes some supported PostgreSQL-specific features. + +## PostgreSQL covering indexes (INCLUDE) + +Since version 11, PostgreSQL supports [covering indexes](https://paquier.xyz/postgresql-2/postgres-11-covering-indexes), which allow you to include "non-key" columns in your indexes. This allows you to perform index-only scans and can provide a significant performance boost: + +```c# +protected override void OnModelCreating(ModelBuilder modelBuilder) + => modelBuilder.Entity() + .HasIndex(b => b.Id) + .ForNpgsqlInclude(b => b.Name); +``` + +This will create an index for searching on `Id`, but containing also the column `Name`, so that reading the latter will not involve accessing the table. The SQL generated is as follows: + +```sql +CREATE INDEX "IX_Blog_Id" ON blogs ("Id") INCLUDE ("Name"); +``` + +## PostgreSQL index methods + +PostgreSQL supports a number of _index methods_, or _types_. These are specified at index creation time via the `USING _method_` clause, see the [PostgreSQL docs for `CREATE INDEX`](https://www.postgresql.org/docs/current/static/sql-createindex.html) and [this page](https://www.postgresql.org/docs/current/static/indexes-types.html) for information on the different types. + +The Npgsql EF Core provider allows you to specify the index method to be used by calling `ForNpgsqlHasMethod()` on your index in your context's `OnModelCreating` method: +```c# +protected override void OnModelCreating(ModelBuilder modelBuilder) + => modelBuilder.Entity() + .HasIndex(b => b.Url) + .ForNpgsqlHasMethod("gin"); +``` + +## PostgreSQL index operator classes + +PostgreSQL allows you to specify [operator classes on your indexes](https://www.postgresql.org/docs/current/indexes-opclass.html), to allow tweaking how the index should work. Use the following code to specify an operator class: + +```c# +protected override void OnConfiguring(DbContextOptionsBuilder builder) + => modelBuilder.Entity() + .ForNpgsqlHasIndex(b => new { b.Id, b.Name }) + .ForNpgsqlHasOperators(null, "text_pattern_ops"); +``` + +Note that each operator class is used for the corresponding index column, by order. In the example above, the `text_pattern_ops` class will be used for the `Name` column, while the `Id` column will use the default class (unspecified), producing the following SQL: + +```sql +CREATE INDEX "IX_blogs_Id_Name" ON blogs ("Id", "Name" text_pattern_ops); +``` diff --git a/docs/modeling/table-column-naming.md b/docs/modeling/table-column-naming.md new file mode 100644 index 0000000000..3f05cabcd5 --- /dev/null +++ b/docs/modeling/table-column-naming.md @@ -0,0 +1,32 @@ +# Table and Column Naming + +By default, EF Core will map to tables and columns named exactly after your .NET classes and properties, so an entity type named `BlogPost` will be mapped to a PostgreSQL table called `BlogPost`. While there's nothing wrong with that, the PostgreSQL world tends towards snake_case naming instead. In addition, any upper-case letters in unquoted identifiers are automatically converted to lower-case identifiers, so the Npgsql provider generates quotes around all such identifiers. + +Starting with 3.0.0, you can use the [EFCore.NamingConventions](https://github.com/efcore/EFCore.NamingConventions) plugin to automatically set all your table and column names to snake_case instead: + +```c# +protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) + => optionsBuilder + .UseNpgsql(...) + .UseSnakeCaseNamingConventions(); + +public class Customer { + public int Id { get; set; } + public string FullName { get; set; } +} +``` + +This will cause cleaner SQL such as the following to be generated: + +```sql +CREATE TABLE customers ( + id integer NOT NULL GENERATED BY DEFAULT AS IDENTITY, + full_name text NULL, + CONSTRAINT "PK_customers" PRIMARY KEY (id); + +SELECT c.id, c.full_name + FROM customers AS c + WHERE c.full_name = 'John Doe'; +``` + +See the [plugin documentation](https://github.com/efcore/EFCore.NamingConventions) for more details, diff --git a/docs/release-notes/1.1.md b/docs/release-notes/1.1.md new file mode 100644 index 0000000000..11a7d3752d --- /dev/null +++ b/docs/release-notes/1.1.md @@ -0,0 +1,30 @@ +# Migrating to 1.1 + +Version 1.1.0 of the Npgsql Entity Framework Core provider has been released and is available on nuget. This version works with [version 1.1.0 of Entity Framework Core](https://blogs.msdn.microsoft.com/dotnet/2016/10/25/announcing-entity-framework-core-1-1-preview-1/), and contains some new Npgsql features as well. Note that if you're using the command-line tools, you'll have to modify your tools section as described in the EF Core release post: + +```json +"tools": { + "Microsoft.EntityFrameworkCore.Tools.DotNet": "1.0.0-preview3-final" +}, +``` + +## New Features + +Aside from general EF Core features, version 1.1.0 of the Npgsql provider contains the following: + +* Hilo key generation ([#5](https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL/issues/5)). This can be a much more efficient way to generate autoincrement key values. +* PostgreSQL array mapping ([#15](https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL/issues/15)). This allows you to have plain CLR arrays on your entities, and have those arrays mapped to native [PostgreSQL array columns](https://www.postgresql.org/docs/current/static/arrays.html). +* Optimistic concurrency with PostgreSQL's xmin column ([#19](https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL/issues/19)). Simply specify `.UseXminAsConcurrencyToken()` on an entity to start using this, see the [EF docs for more details](https://docs.efproject.net/en/latest/modeling/concurrency.html). +* Cleanup of how serial (autoincrement) and generated GUID/UUID columns are managed. + +Here's the [full list of issues](https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL/milestone/3?closed=1). Please report any problems to https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL. + +## Upgrading from 1.0.x + +If you've used 1.0.x without migrations, you can simply upgrade and everything should just work. Unfortunately, if you already have migrations from 1.0.x you'll have to do some manual fixups because of some bad decisions that were previously made. If deleting your old migrations and starting over (e.g. non-production database) is an option, you may wish to do so. The following are instructions for fixing up 1.0.x migrations. + +First, Npgsql 1.0.x used a problematic method to identify serial (autoincrement) columns in migrations. If you look at your migration code you'll see `.Annotation("Npgsql:ValueGeneratedOnAdd", true)` on various columns. Unfortunately this annotation is also present on non-serial columns, e.g. columns with default values. This causes various issues and has been replaced in 1.1. However, you'll have to manually remove `.Annotation("Npgsql:ValueGeneratedOnAdd", true)`, and replace it with `.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.SerialColumn)` but *only* on columns which should be serial (e.g. not on columns with defaults). If you attempt to run a migration that has the old annotation, Npgsql will throw an exception and refuse to run your migrations. + +Unfortunately, this change will cause some incorrect changes the first time you add a migration after the upgrade. To avoid this, simply add a dummy migration right after upgrading to 1.1 and then delete the two new files generated for the dummy migration, *but keep the changes made to your ModelSnapshot.cs*. From this point on everything should be fine. *Make sure you have no pending changes to your model before doing this!*. + +Apologies for this problematic upgrade procedure, it should at least keep things clean going forward. diff --git a/docs/release-notes/2.0.md b/docs/release-notes/2.0.md new file mode 100644 index 0000000000..3ef18f78a3 --- /dev/null +++ b/docs/release-notes/2.0.md @@ -0,0 +1,19 @@ +# 2.0 Release Notes + +Version 2.0.0 of the Npgsql Entity Framework Core provider has been released and is available on [nuget.org](https://www.nuget.org/packages/Npgsql.EntityFrameworkCore.PostgreSQL). This version works with [version 2.0.0 of Entity Framework Core](https://blogs.msdn.microsoft.com/dotnet/2017/08/14/announcing-entity-framework-core-2-0/), and contains some new Npgsql features as well. + +## New Features + +Aside from general EF Core features new in 2.0.0, the Npgsql provider contains the following major new features: + +* PostgreSQL array operation translation ([#120](https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL/issues/120)). While array properties have been supported since 1.1, operations on those arrays where client-evaluated. Version 2.0 will now translate array indexing, `.Contains()`, `.SequenceEquals()` and `.Length`. See the [array mapping docs](../mapping/array.md) for more details. +* A retrying execution strategy ([#155](https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL/issues/155)), which will automatically retry operations on exceptions which are considered transient. +* PostgreSQL extensions are now included in scaffolded models ([#102](https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL/issues/102)). +* More LINQ operations are translated to SQL, and more database scenarios are scaffolded correctly (see [the docs](http://www.npgsql.org/efcore/mapping-and-translation.html)). + +Here's the [full list of issues](https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL/milestone/6?closed=1). Please report any problems to https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL. + +## Upgrading from 1.x + +* Previously an Npgsql.EntityFrameworkCore.PostgreSQL.Design nuget package existed alongside the main package. Its contents have been merged into the main Npgsql.EntityFrameworkCore.PostgreSQL and no new version has been released. +* Specifying versions when specifying PostgreSQL extensions on your model is no longer supported - this was a very rarely-used feature which interfered with extension scaffolding. diff --git a/docs/release-notes/2.1.md b/docs/release-notes/2.1.md new file mode 100644 index 0000000000..4ef3301ef3 --- /dev/null +++ b/docs/release-notes/2.1.md @@ -0,0 +1,81 @@ +# 2.1 Release Notes + +Version 2.1.0 of the Npgsql Entity Framework Core provider has been released and is available on nuget. This version works with [version 2.1.0 of Entity Framework Core](https://docs.microsoft.com/ef/core/what-is-new/ef-core-2.1), and contains some new Npgsql features as well. + +Thanks to [@rwasef1830](https://github.com/rwasef1830) and [@austindrenski](https://github.com/austindrenski) for their valuable contributions. + +## New Features + +Aside from general EF Core features new in 2.1.0, the Npgsql provider contains the following major new features: + +### Improved Spatial Support (PostGIS) + +Previous versions have allowed basic usage of PostGIS's spatial types via built-in Npgsql types such as `NpgsqlPoint`, `NpgsqlLineString`, etc. These types were limited in many ways, and no operation translation was supported. If you want to calculate, say, the distance between two points, you had to drop down to raw SQL. + +No more! Thanks to a new plugin infrastructure, the EF Core provider now has full-class support for PostGIS. You can now use the [NetTopologySuite](https://github.com/NetTopologySuite/NetTopologySuite) spatial library to map PostGIS types - NetTopologySuite's types are more complete, and best of all, the provider knows how to translate its operations to SQL. This allows you to write the following code: + +```c# +var nearbyCities = context.Cities.Where(c => c.Location.Distance(somePoint) < 100); +``` + +See [the full documentation for more information](../mapping/nts.md). + +Thanks to [@YohDeadfall](https://github.com/YohDeadfall) for implementing support for this at the ADO level. + +### Full text search + +PostgreSQL has a powerful feature for efficient natural-language search across multiple columns and tables, [see the PostgreSQL docs for more info](https://www.postgresql.org/docs/current/static/textsearch.html). The EF Core provider now supports full-text search, allowing you to use .NET functions in your LINQ queries which will get translated to efficient PostgreSQL natural-language search queries. + +Read [the full documentation for more information](../mapping/full-text-search.md). + +Many thanks to [@rwasef1830](https://github.com/rwasef1830) for contributing this feature. + +### NodaTime date/time support + +[NodaTime](https://nodatime.org) is a powerful alternative to .NET's built-in date/time types, such as `DateTime`. The built-in types are flawed in many ways: they have problematic support for timezones, don't have a date-only or time-only types, and promote problematic programming but not making the right distinctions. If your application handles dates and times in anything but the most basic way, you should seriously consider using NodaTime. To learn more read [this blog post by Jon Skeet](https://blog.nodatime.org/2011/08/what-wrong-with-datetime-anyway.html). + +Thanks to a new plugin infrastructure, it is now possible to set up the EF Core provider to use NodaTime's types instead of the built-in .NET ones; instead of having `DateTime` properties on your entities, you can now have [Instant](https://nodatime.org/2.2.x/userguide/core-types) properties instead. + +See [the full documentation for more information](../mapping/nodatime.md). + +### PostgreSQL 10 IDENTITY columns + +PostgreSQL 10 introduced a new IDENTITY column as an alternative to traditional SERIAL columns, and these are now supported by the EF Core provider. IDENTITY columns conform to the SQL standard and are in general safer than SERIAL columns, [read this blog post for more info](https://docs.microsoft.com/ef/core/what-is-new/ef-core-2.1). It's recommended that all new projects use IDENTITY, but Npgsql even provides seamless migration of your existing SERIAL-based model!. + +Read [the full documentation for more information](../modeling/generated-properties.md). + +### Enum support + +It is now possible to map your CLR enums to [native PostgreSQL enums](https://www.postgresql.org/docs/current/static/datatype-enum.html). This is a unique PostgreSQL feature that provides the best of both worlds: the enum is internally stored in the database as a number (minimal storage), but is handled like a string (more usable, no need to remember numeric values) and has type safety. + +See [the full documentation for more information](../mapping/enum.md). + +### Range support + +PostgreSQL supports [native range types](https://www.postgresql.org/docs/current/static/rangetypes.html), which allow you to represent ranges of dates, ints and other data types in a single column. You can then efficiently perform queries on these types from LINQ, e.g. select all rows where a given date falls in the row's date range. + +See [the full documentation for more information](../mapping/range.md). + +Many thanks to [@austindrenski](https://github.com/austindrenski) for contributing the operation translations. + +### Other notable features + +* Several improvements have been made to the way arrays are mapped. For example, you can now map `List` to PostgreSQL array (previously only `T[]` was supported) ([#392](https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL/issues/392)). In addition, change tracking now works for arrays, so EF Core will automatically detect when you change an element's array and will update the corresponding database column when saving. +* PostgreSQL's built-in range types can now be mapped ([#63](https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL/issues/63)), head over to the [PostgreSQL docs](https://www.postgresql.org/docs/current/static/rangetypes.html) to find out more about range types. Note that user-defined range types are *not* supported, if you're interested let us know at [#329](https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL/issues/329). +* Properties of type `char` are now supported and will be mapped to `character(1)` in PostgreSQL ([#374](https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL/issues/374)). +* Identifiers in generated SQL will only be quoted if needed ([#327](https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL/issues/327)). This should make it much easier to read. +* You can now use client certificate authentication and provide a server certificate validation callback ([#270](https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL/issues/270)). See [the doc for usage instructions](http://www.npgsql.org/efcore/misc.html#certificate-authentication). +* Added support for PostgreSQL 10 sequences with type `int` and `smallint` ([#301](https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL/issues/301)). +* You can now specify the [tablespace](https://www.postgresql.org/docs/current/static/manage-ag-tablespaces.html) when creating your databases ([#332](https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL/issues/332)). + +Here's the [full list of issues](https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL/milestone/8?closed=1). Please report any problems on https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL. + +## Breaking changes + +> [!CAUTION] +> The provider's classes have been moved from the namespace `Microsoft.EntityFrameworkCore` to `Npgsql.EntityFrameworkCore.PostgreSQL`. As a result, any migrations already generated in your project (as well as the mode snapshot) will have to be manually updated to use the new namespace. You will need to add `using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata` to all the relevant files. + +* Columns of type `timestamp with time zone`/`timestamptz` will now be scaffolded as `DateTime` properties, and not `DateTimeOffset` properties. The general use of `timestamp with time zone`/`timestamptz` is discouraged (this type does *not* store the timezone in the database), consider using `timestamp without time zone`/`timestamp` instead. +* If you're specifying index methods with `ForNpgsqlHasMethod()`, then you will have to fix migrations which generate those indexes. In these migrations, you will find code such as `.Annotation("Npgsql:Npgsql:IndexMethod", "gin")`. You must remove the extra `Npgsql:`, leaving `.Annotation("Npgsql:IndexMethod", "gin")`. +* Specifying versions when specifying PostgreSQL extensions on your model is no longer supported - this was a very rarely-used feature which interfered with extension scaffolding. +* If you're still referencing the nuget package Npgsql.EntityFrameworkCore.PostgreSQL.Design, please remove it - it's no longer needed or up to date. diff --git a/docs/release-notes/2.2.md b/docs/release-notes/2.2.md new file mode 100644 index 0000000000..fb8e8bae47 --- /dev/null +++ b/docs/release-notes/2.2.md @@ -0,0 +1,57 @@ +# 2.2 Release Notes + +Version 2.2.0 of the Npgsql Entity Framework Core provider has been released and is available on nuget. This version works with [version 2.2.0 of Entity Framework Core](https://docs.microsoft.com/ef/core/what-is-new/ef-core-2.2), and contains some new Npgsql features as well. + +This release was result of hard work by [@roji](https://github.com/roji/), [@austindrenski](https://github.com/austindrenski), [@yohdeadfall](https://github.com/yohdeadfall) and [@khellang](https://github.com/khellang). + +## New Features + +Aside from general EF Core features new in 2.2.0, the Npgsql EF Core provider contains the following major new features: + +### PostgreSQL 11 covering indexes + +PostgreSQL 11 introduced [covering indexes feature](https://paquier.xyz/postgresql-2/postgres-11-covering-indexes), which allow you to include "non-key" columns in your indexes. This allows you to perform index-only scans and can provide a significant performance boost. Support has been added in ([#697](https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL/issues/697)): + +```c# +protected override void OnConfiguring(DbContextOptionsBuilder builder) + => modelBuilder.Entity() + .ForNpgsqlHasIndex(b => b.Id) + .ForNpgsqlInclude(b => b.Name); +``` + +This will create an index for searching on `Id`, but containing also the column `Name`, so that reading the latter will not involve accessing the table. [See the documentation for more details](../modeling/indexes.md). + +Thanks to [@khellang](https://github.com/khellang) for contributing this! + +### PostgreSQL user-defined ranges + +The provider already supported [PostgreSQL range types](https://www.postgresql.org/docs/current/rangetypes.html), but prior to 2.2 that support was limited to the built-in range types which come with PostgreSQL. [#329](https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL/issues/329) extends that support to range types which you define: + +```c# +protected override void OnConfiguring(DbContextOptionsBuilder builder) + => builder.UseNpgsql("...", b => b.MapRange("floatrange")); + +protected override void OnModelCreating(ModelBuilder builder) + => builder.ForNpgsqlHasRange("floatrange", "real"); +``` + +This will make the provider create a PostgreSQL range called `floatrange`, over the PostgreSQL type `real`. Any property with type `NpgsqlRange` will be seamlessly mapped to it. + +[See the documentation for more details](../mapping/range.md). + +### Seeding for Npgsql-specific types + +When using some Npgsql-specific types, it wasn't possible to seed values for those types. With EF Core support for seeding any type, [#667](https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL/issues/667) allows seeding values for network, bit and range types (more are coming). + +### PostgreSQL index operator classes + +PostgreSQL allows you to specify [operator classes on your indexes](https://www.postgresql.org/docs/current/indexes-opclass.html), to allow tweaking how the index should work. [#481](https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL/issues/481) adds support for managing these. [See the documentation for more details](../modeling/indexes.md). + +Thanks to [@khellang](https://github.com/khellang) for contributing this! + +### Other features + +* Various issues with enum and range types were fixed, including upper/lower case, quoting and schema management. +* Many new SQL translations were added, so more of your LINQ expressions can run in the database. We'll be working on our documentation to make these more discoverable. + +The full list of issues for this release is [available here](https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL/issues?q=milestone%3A2.2.0+is%3Aclosed&utf8=%E2%9C%93). diff --git a/docs/release-notes/3.0.md b/docs/release-notes/3.0.md new file mode 100644 index 0000000000..6942c3ac09 --- /dev/null +++ b/docs/release-notes/3.0.md @@ -0,0 +1,49 @@ +# 3.0 Release Notes + +Version 3.0.0 of the Npgsql Entity Framework Core provider has been released and is available on nuget. This version works with [version 3.0.0 of Entity Framework Core](https://docs.microsoft.com/ef/core/what-is-new/ef-core-3.0), and bring new Npgsql features in addition to the general EF Core changes. + +> [!CAUTION] +> Use these versions with care and do not deploy to production without thorough testing. Read the breaking changes section below. + +The full list of issues for this release is [available here](https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL/milestone/20?closed=1). + +## New Features + +Aside from general EF Core features new in 3.0.0, the Npgsql EF Core provider contains the following major new features: + +* It is now possible to map POCOs to JSON columns and query them, [see the docs for more info](../mapping/json.md) ([#981](https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL/issues/981)) +* PostgreSQL identity columns are now the default - see breaking changes below) ([#804](https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL/issues/804)) +* Sequence options can now be managed on identity columns ([#819](https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL/issues/819)) +* Support has been added for the upcoming [PostgreSQL 12 generated columns feature](https://www.postgresql.org/docs/12/ddl-generated-columns.html) ([#939](https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL/issues/939)) +* A plugin is now available to automatically make all your tables and columns be snake_case! See [EFCore.NamingConventions](https://github.com/efcore/EFCore.NamingConventions). +* Index sort options (ascending/descending, null sort order...) can now be specified ([#326](https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL/issues/326)) +* Indexes can now be created concurrently ([#967](https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL/issues/967)) +* Views are now reverse-engineered ([#878](https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL/issues/878)) +* Array value converters help mapping with PostgreSQL arrays (e.g. map enum arrays to integer arrays) ([#1031](https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL/issues/1031)). + +## Breaking changes + +### Default value generation strategy is now IDENTITY + +> [!CAUTION] +> This is a major change, and upgrading to 3.0 with an existing database will cause a non-trivial schema migration to be generated. Read the following carefully. + +The default value generation strategy has changed from the older SERIAL columns to the newer IDENTITY columns, introduced in PostgreSQL 10. + +When producing a migration with 3.0, the Npgsql provider will attempt to automatically generate SQL to alter your tables and convert serial columns to identity ones. This is a sensitive, one-time migration operation that should be done with care, and carefully tested before deployment to production. + +If you wish to opt out of using IDENTITY columns and continue using SERIAL columns, set the following on your model: + +```c# +protected override void OnModelCreating(ModelBuilder modelBuilder) + => modelBuilder.UseSerialColumns(); +``` + +If you are using a PostgreSQL version older than 10, setting the compatibility mode is a better to to switch the default back to SERIAL columns: + +```c# +protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) + => optionsBuilder.UseNpgsql("...", o => o.SetPostgresVersion(9, 6)); +``` + +More information is available in [the page about generated properties](../modeling/generated-properties.md). diff --git a/docs/toc.md b/docs/toc.md new file mode 100644 index 0000000000..39f97a75ca --- /dev/null +++ b/docs/toc.md @@ -0,0 +1,22 @@ +# [Getting Started](index.md) +# Release Notes +## [3.0](release-notes/3.0.md) +## [2.2](release-notes/2.2.md) +## [2.1](release-notes/2.1.md) +## [2.0](release-notes/2.0.md) +## [1.1](release-notes/1.1.md) +# Creating a Model +## [Table and Column Naming](modeling/table-column-naming.md) +## [Generated Properties](modeling/generated-properties.md) +## [Indexes](modeling/indexes.md) +# Mapping and Translation +## [General](mapping/general.md) +## [JSON](mapping/json.md) +## [Spatial Data](mapping/nts.md) +## [Full Text Search](mapping/full-text-search.md) +## [NodaTime](mapping/nodatime.md) +## [Arrays](mapping/array.md) +## [Enums](mapping/enum.md) +## [Ranges](mapping/range.md) +# [Miscellaneous](miscellaneous.md) +# [API Reference](../../obj/api/EFCore.PG/) From 07d43130b6d3cdc46c71f2280038ae3e154c13fa Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Thu, 26 Sep 2019 16:14:30 +0200 Subject: [PATCH 002/207] Tiny grammar fix --- docs/release-notes/3.0.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/release-notes/3.0.md b/docs/release-notes/3.0.md index 6942c3ac09..aa8cc4de8d 100644 --- a/docs/release-notes/3.0.md +++ b/docs/release-notes/3.0.md @@ -39,7 +39,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) => modelBuilder.UseSerialColumns(); ``` -If you are using a PostgreSQL version older than 10, setting the compatibility mode is a better to to switch the default back to SERIAL columns: +If you are using a PostgreSQL version older than 10, setting the compatibility mode is a better way to switch the default back to SERIAL columns: ```c# protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) From fba4f3aa83c3e5f39089f279e43c415161be87e5 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Mon, 30 Sep 2019 15:16:53 +0200 Subject: [PATCH 003/207] Move concurrency information from misc to modeling --- docs/miscellaneous.md | 14 -------------- docs/modeling/concurrency.md | 18 ++++++++++++++++++ docs/toc.md | 1 + 3 files changed, 19 insertions(+), 14 deletions(-) create mode 100644 docs/modeling/concurrency.md diff --git a/docs/miscellaneous.md b/docs/miscellaneous.md index 6e60475be6..2a24efb50c 100644 --- a/docs/miscellaneous.md +++ b/docs/miscellaneous.md @@ -10,20 +10,6 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) => modelBuilder.HasPostgresExtension("hstore"); ``` -## Optimistic Concurrency and Concurrency Tokens - -Entity Framework Core supports the concept of optimistic concurrency - a property on your entity is designated as a concurrency token, and EF Core detects concurrent modifications by checking whether that token has changed since the entity was read. You can read more about this in the [EF Core docs](https://docs.microsoft.com/ef/core/modeling/concurrency). - -Although applications can update concurrency tokens themselves, we frequently rely on the database automatically updating a column on update - a "last modified" timestamp, an SQL Server `rowversion`, etc. Unfortunately PostgreSQL doesn't have such auto-updating columns - but there is one feature that can be used for concurrency token. All PostgreSQL tables have a set of [implicit and hidden system columns](https://www.postgresql.org/docs/current/static/ddl-system-columns.htm://www.postgresql.org/docs/current/static/ddl-system-columns.html), among which `xmin` holds the ID of the latest updating transaction. Since this value automatically gets updated every time the row is changed, it is ideal for use as a concurrency token. - -To enable this feature on an entity, insert the following code into your context's `OnModelCreating` method: - -```c# -protected override void OnModelCreating(ModelBuilder modelBuilder) - => modelBuilder.Entity() - .ForNpgsqlUseXminAsConcurrencyToken(); -``` - ## Execution Strategy Since 2.0.0, the Npgsql EF Core provider provides a retrying execution strategy, which will attempt to detect most transient PostgreSQL/network errors and will automatically retry your operation. To enable, place the following code in your context's `OnModelConfiguring`: diff --git a/docs/modeling/concurrency.md b/docs/modeling/concurrency.md new file mode 100644 index 0000000000..2a99e4a74d --- /dev/null +++ b/docs/modeling/concurrency.md @@ -0,0 +1,18 @@ +# Concurrency Tokens + +> [!NOTE] +> Please read the general [Entity Framework Core docs on concurrency tokens](https://docs.microsoft.com/en-us/ef/core/modeling/concurrency). + +Entity Framework Core supports the concept of optimistic concurrency - a property on your entity is designated as a concurrency token, and EF Core detects concurrent modifications by checking whether that token has changed since the entity was read. + +## The PostgreSQL xmin system column + +Although applications can update concurrency tokens themselves, we frequently rely on the database automatically updating a column on update - a "last modified" timestamp, an SQL Server `rowversion`, etc. Unfortunately PostgreSQL doesn't have such auto-updating columns - but there is one feature that can be used for concurrency token. All PostgreSQL tables have a set of [implicit and hidden system columns](https://www.postgresql.org/docs/current/static/ddl-system-columns.htm://www.postgresql.org/docs/current/static/ddl-system-columns.html), among which `xmin` holds the ID of the latest updating transaction. Since this value automatically gets updated every time the row is changed, it is ideal for use as a concurrency token. + +To enable this feature on an entity, insert the following code into your context's `OnModelCreating` method: + +```c# +protected override void OnModelCreating(ModelBuilder modelBuilder) + => modelBuilder.Entity() + .ForNpgsqlUseXminAsConcurrencyToken(); +``` diff --git a/docs/toc.md b/docs/toc.md index 39f97a75ca..f4885c8ff7 100644 --- a/docs/toc.md +++ b/docs/toc.md @@ -8,6 +8,7 @@ # Creating a Model ## [Table and Column Naming](modeling/table-column-naming.md) ## [Generated Properties](modeling/generated-properties.md) +## [Concurrency Tokens](modeling/concurrency.md) ## [Indexes](modeling/indexes.md) # Mapping and Translation ## [General](mapping/general.md) From ab6489ee35230f1390cf3a1e1bb4b4cb5fa683c6 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Mon, 30 Sep 2019 23:05:21 +0200 Subject: [PATCH 004/207] Fix API naming changes in EFCore.PG 3.0.0 Removal of ForNpgsql from metadata methods --- docs/mapping/enum.md | 6 +++--- docs/mapping/full-text-search.md | 2 +- docs/mapping/range.md | 4 ++-- docs/miscellaneous.md | 6 +++--- docs/modeling/concurrency.md | 2 +- docs/modeling/generated-properties.md | 6 +++--- docs/modeling/indexes.md | 10 +++++----- 7 files changed, 18 insertions(+), 18 deletions(-) diff --git a/docs/mapping/enum.md b/docs/mapping/enum.md index 42a4ede376..f59774b325 100644 --- a/docs/mapping/enum.md +++ b/docs/mapping/enum.md @@ -12,14 +12,14 @@ First, you must specify the PostgreSQL enum type on your model, just like you wo ```c# protected override void OnModelCreating(ModelBuilder builder) - => builder.ForNpgsqlHasEnum(); + => builder.HasPostgresEnum(); ``` # [Version 2.1](#tab/tabid-2) ```c# protected override void OnModelCreating(ModelBuilder builder) - => builder.ForNpgsqlHasEnum("Mood", new[] { "happy", "sad" }); + => builder.HasPostgresEnum("Mood", new[] { "happy", "sad" }); ``` --- @@ -68,7 +68,7 @@ Although PostgreSQL allows [altering enum types](https://www.postgresql.org/docs ## Scaffolding from an existing database -If you're creating your model from an existing database, the provider will recognize enums in your database, and scaffold the appropriate `ForNpgsqlHasEnum()` lines in your model. However, since the scaffolding process has no knowledge of your CLR type, and will therefore skip your enum columns (warnings will be logged). You will have to create the CLR type, add the global mapping and add the properties to your entities. +If you're creating your model from an existing database, the provider will recognize enums in your database, and scaffold the appropriate `HasPostgresEnum()` lines in your model. However, since the scaffolding process has no knowledge of your CLR type, and will therefore skip your enum columns (warnings will be logged). You will have to create the CLR type, add the global mapping and add the properties to your entities. In the future it may be possible to scaffold the actual enum type (and with it the properties), but this doesn't happen at the moment. diff --git a/docs/mapping/full-text-search.md b/docs/mapping/full-text-search.md index da790b1ab7..2234706bfd 100644 --- a/docs/mapping/full-text-search.md +++ b/docs/mapping/full-text-search.md @@ -91,7 +91,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity() .HasIndex(p => p.SearchVector) - .ForNpgsqlHasMethod("GIN"); // Index method on the search vector (GIN or GIST) + .HasMethod("GIN"); // Index method on the search vector (GIN or GIST) } ``` diff --git a/docs/mapping/range.md b/docs/mapping/range.md index 3bec36b78e..db43b32994 100644 --- a/docs/mapping/range.md +++ b/docs/mapping/range.md @@ -38,10 +38,10 @@ The above does *not* create the `floatrange` type for you. In order to do that, ```c# protected override void OnModelCreating(ModelBuilder modelBuilder) - => modelBuilder.ForNpgsqlHasRange("floatrange", "real"); + => modelBuilder.HasPostgresRange("floatrange", "real"); ``` -This will cause the appropriate [`CREATE TYPE ... AS RANGE`](https://www.postgresql.org/docs/current/static/sql-createtype.html) statement to be generated in your migrations, ensuring that your range is created and ready for use. Note that `ForNpgsqlHasRange()` supports additional parameters as supported by PostgreSQL `CREATE TYPE`. +This will cause the appropriate [`CREATE TYPE ... AS RANGE`](https://www.postgresql.org/docs/current/static/sql-createtype.html) statement to be generated in your migrations, ensuring that your range is created and ready for use. Note that `HasPostgresRange()` supports additional parameters as supported by PostgreSQL `CREATE TYPE`. # Operation translation diff --git a/docs/miscellaneous.md b/docs/miscellaneous.md index 2a24efb50c..06f5607951 100644 --- a/docs/miscellaneous.md +++ b/docs/miscellaneous.md @@ -30,7 +30,7 @@ PostgreSQL allows you to [attach comments](https://www.postgresql.org/docs/curre ```c# protected override void OnModelCreating(ModelBuilder modelBuilder) => modelBuilder.Entity() - .ForNpgsqlHasComment("Some comment"); + .HasComment("Some comment"); ``` ## Certificate authentication @@ -84,7 +84,7 @@ PostgreSQL allows you to locate your database in different parts of your filesys ```c# protected override void OnModelCreating(ModelBuilder modelBuilder) - => modelBuilder.ForNpgsqlUseTablespace("my_tablespace"); + => modelBuilder.UseTablespace("my_tablespace"); ``` You must have created your tablespace prior to this via the `CREATE TABLESPACE` command - the Npgsql EF Core provider does not do this for you. Note also that specifying a tablespace on specific tables is not supported. @@ -96,7 +96,7 @@ If you're using CockroachDB, the Npgsql EF Core provider exposes its ["interleav ```c# protected override void OnModelCreating(ModelBuilder modelBuilder) => modelBuilder.Entity() - .ForCockroachDbInterleaveInParent( + .UseCockroachDbInterleaveInParent( typeof(ParentEntityType), new List { "prefix_column_1", "prefix_column_2" }); ``` diff --git a/docs/modeling/concurrency.md b/docs/modeling/concurrency.md index 2a99e4a74d..c43a3cd025 100644 --- a/docs/modeling/concurrency.md +++ b/docs/modeling/concurrency.md @@ -14,5 +14,5 @@ To enable this feature on an entity, insert the following code into your context ```c# protected override void OnModelCreating(ModelBuilder modelBuilder) => modelBuilder.Entity() - .ForNpgsqlUseXminAsConcurrencyToken(); + .UseXminAsConcurrencyToken(); ``` diff --git a/docs/modeling/generated-properties.md b/docs/modeling/generated-properties.md index 875b1653ae..bea8e08359 100644 --- a/docs/modeling/generated-properties.md +++ b/docs/modeling/generated-properties.md @@ -59,20 +59,20 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) One disadvantage of database-generated values is that these values must be read back from the database after a row is inserted. If you're saving multiple related entities, this means you must perform multiple roundtrips as the first entity's generated key must be read before writing the second one. One solution to this problem is HiLo value generation: rather than relying on the database to generate each and every value, the application "allocates" a range of values, which it can then populate directly on new entities without any additional roundtrips. When the range is exhausted, a new range is allocated. In practical terms, this uses a sequence that increments by some large value (100 by default), allowing the application to insert 100 rows autonomously. -To use HiLo, specify `ForNpgsqlUseSequenceHiLo` on a property in your model's `OnModelCreating`: +To use HiLo, specify `UseHiLo` on a property in your model's `OnModelCreating`: ```c# protected override void OnModelCreating(ModelBuilder modelBuilder) => modelBuilder.Entity() .Property(b => b.Id) - .ForNpgsqlUseSequenceHiLo(); + .UseHiLo(); ``` You can also make your model use HiLo everywhere: ```c# protected override void OnModelCreating(ModelBuilder modelBuilder) - => modelBuilder.ForNpgsqlUseSequenceHiLo(); + => modelBuilder.UseHiLo(); ``` ## Guid/UUID Generation diff --git a/docs/modeling/indexes.md b/docs/modeling/indexes.md index 9a869b7b7d..4ffc12052a 100644 --- a/docs/modeling/indexes.md +++ b/docs/modeling/indexes.md @@ -10,7 +10,7 @@ Since version 11, PostgreSQL supports [covering indexes](https://paquier.xyz/pos protected override void OnModelCreating(ModelBuilder modelBuilder) => modelBuilder.Entity() .HasIndex(b => b.Id) - .ForNpgsqlInclude(b => b.Name); + .IncludeProperties(b => b.Name); ``` This will create an index for searching on `Id`, but containing also the column `Name`, so that reading the latter will not involve accessing the table. The SQL generated is as follows: @@ -23,12 +23,12 @@ CREATE INDEX "IX_Blog_Id" ON blogs ("Id") INCLUDE ("Name"); PostgreSQL supports a number of _index methods_, or _types_. These are specified at index creation time via the `USING _method_` clause, see the [PostgreSQL docs for `CREATE INDEX`](https://www.postgresql.org/docs/current/static/sql-createindex.html) and [this page](https://www.postgresql.org/docs/current/static/indexes-types.html) for information on the different types. -The Npgsql EF Core provider allows you to specify the index method to be used by calling `ForNpgsqlHasMethod()` on your index in your context's `OnModelCreating` method: +The Npgsql EF Core provider allows you to specify the index method to be used by calling `HasMethod()` on your index in your context's `OnModelCreating` method: ```c# protected override void OnModelCreating(ModelBuilder modelBuilder) => modelBuilder.Entity() .HasIndex(b => b.Url) - .ForNpgsqlHasMethod("gin"); + .HasMethod("gin"); ``` ## PostgreSQL index operator classes @@ -38,8 +38,8 @@ PostgreSQL allows you to specify [operator classes on your indexes](https://www. ```c# protected override void OnConfiguring(DbContextOptionsBuilder builder) => modelBuilder.Entity() - .ForNpgsqlHasIndex(b => new { b.Id, b.Name }) - .ForNpgsqlHasOperators(null, "text_pattern_ops"); + .HasIndex(b => new { b.Id, b.Name }) + .HasOperators(null, "text_pattern_ops"); ``` Note that each operator class is used for the corresponding index column, by order. In the example above, the `text_pattern_ops` class will be used for the `Name` column, while the `Id` column will use the default class (unspecified), producing the following SQL: From 6880a57cc64df2768993bf256464ef27e3bb942b Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Mon, 30 Sep 2019 23:38:41 +0200 Subject: [PATCH 005/207] Correct ASP.NET getting started instructions --- docs/index.md | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/docs/index.md b/docs/index.md index bb32dcaee2..d476cf5438 100644 --- a/docs/index.md +++ b/docs/index.md @@ -67,13 +67,16 @@ namespace ConsoleApp.PostgreSQL ## Additional configuration for ASP.NET Core applications -Modify the `ConfigureServices` method in `Startup.cs`: +Consult [this tutorial](https://docs.microsoft.com/en-us/aspnet/core/data/ef-rp/intro) for general information on how to make ASP.NET work with EF Core. For Npgsql specifically, simply place the following in your `ConfigureServices` method in `Startup.cs`: ```c# -public IServiceProvider ConfigureServices(IServiceCollection services) - => services.AddEntityFrameworkNpgsql() - .AddDbContext() - .BuildServiceProvider(); +public void ConfigureServices(IServiceCollection services) +{ + // Other DI initializations + + services.AddDbContext(options => + options.UseNpgsql(Configuration.GetConnectionString("BloggingContext"))); +} ``` ## Using an Existing Database (Database-First) From 86d7b66f70303df009ebe8f4722662aadf216eb1 Mon Sep 17 00:00:00 2001 From: damageboy <125730+damageboy@users.noreply.github.com> Date: Wed, 30 Oct 2019 09:49:15 +0200 Subject: [PATCH 006/207] Update to .NET Core 3.0 --- docs/index.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/index.md b/docs/index.md index d476cf5438..33d7b66548 100644 --- a/docs/index.md +++ b/docs/index.md @@ -20,10 +20,10 @@ Below is a `.csproj` file for a console application that uses the Npgsql EF Core ```xml - netcoreapp2.2 + netcoreapp3.0 - + ``` From df5663f8c63494741fc2bcc74b3dec3d8449cee0 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Mon, 25 Nov 2019 19:37:45 +0100 Subject: [PATCH 007/207] Document array overlap & containment support https://github.com/npgsql/efcore.pg/issues/1135 --- docs/mapping/array.md | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/docs/mapping/array.md b/docs/mapping/array.md index 271bf8a614..505129c3b3 100644 --- a/docs/mapping/array.md +++ b/docs/mapping/array.md @@ -27,9 +27,11 @@ The provider can also translate CLR array operations to the corresponding SQL op Note that operation translation on `List<>` is limited at this time, but will be improved in the future. It's recommended to use an array for now. -| C# expression | SQL generated by Npgsql | -|------------------------------------------------------------|-------------------------| -| `.Where(c => c.SomeArray[1] == "foo")` | [`WHERE "c"."SomeArray"[1] = 'foo'`](https://www.postgresql.org/docs/current/static/arrays.html#ARRAYS-ACCESSING) -| `.Where(c => c.SomeArray.SequenceEqual(new[] { 1, 2, 3 })` | [`WHERE "c"."SomeArray" = ARRAY[1, 2, 3])`](https://www.postgresql.org/docs/current/static/arrays.html) -| `.Where(c => c.SomeArray.Contains(3))` | [`WHERE 3 = ANY("c"."SomeArray")`](https://www.postgresql.org/docs/current/static/functions-comparisons.html#AEN21104) -| `.Where(c => c.SomeArray.Length == 3)` | [`WHERE cardinality("c"."SomeArray") = 3`](https://www.postgresql.org/docs/current/static/functions-array.html#ARRAY-FUNCTIONS-TABLE) +| C# expression | SQL generated by Npgsql | +|-----------------------------------------------------------------|-------------------------| +| `.Where(c => c.SomeArray[1] == "foo")` | [`WHERE c."SomeArray"[1] = 'foo'`](https://www.postgresql.org/docs/current/static/arrays.html#ARRAYS-ACCESSING) +| `.Where(c => c.SomeArray.SequenceEqual(new[] { 1, 2, 3 })` | [`WHERE c."SomeArray" = ARRAY[1, 2, 3])`](https://www.postgresql.org/docs/current/static/arrays.html) +| `.Where(c => c.SomeArray.Contains(3))` | [`WHERE 3 = ANY(c."SomeArray")`](https://www.postgresql.org/docs/current/static/functions-comparisons.html#AEN21104) +| `.Where(c => c.SomeArray.Length == 3)` | [`WHERE cardinality(c."SomeArray") = 3`](https://www.postgresql.org/docs/current/static/functions-array.html#ARRAY-FUNCTIONS-TABLE) +| `.Where(c => c.SomeArray.Any(i => someOtherArray.Contains(i)))` | [`WHERE c."SomeArray" && @someOtherArray`](https://www.postgresql.org/docs/current/functions-array.html#ARRAY-OPERATORS-TABLE) +| `.Where(c => c.SomeArray.All(i => someOtherArray.Contains(i)))` | [`WHERE c."SomeArray" <@ @someOtherArray`](https://www.postgresql.org/docs/current/functions-array.html#ARRAY-OPERATORS-TABLE) From be91eaa2f046a5368d4c1e67169941bfc732c812 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Sat, 28 Dec 2019 12:43:34 +0100 Subject: [PATCH 008/207] Tiny: add plus to version --- docs/mapping/enum.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/mapping/enum.md b/docs/mapping/enum.md index f59774b325..3a940544bd 100644 --- a/docs/mapping/enum.md +++ b/docs/mapping/enum.md @@ -8,7 +8,7 @@ However, the Npgsql provider also allows you to map your CLR enums to [database First, you must specify the PostgreSQL enum type on your model, just like you would with tables, sequences or other databases objects: -# [Version 2.2](#tab/tabid-1) +# [Version 2.2+](#tab/tabid-1) ```c# protected override void OnModelCreating(ModelBuilder builder) From 3c29fd17c6055f74257e1400f6401a3f213deada Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Mon, 6 Jan 2020 20:06:23 +0100 Subject: [PATCH 009/207] Add some nice tabs --- docs/mapping/general.md | 18 ++++++++++++------ docs/mapping/json.md | 4 ++-- 2 files changed, 14 insertions(+), 8 deletions(-) diff --git a/docs/mapping/general.md b/docs/mapping/general.md index 5cc4b691cc..acca824aaf 100644 --- a/docs/mapping/general.md +++ b/docs/mapping/general.md @@ -21,13 +21,9 @@ Special types such as [arrays](array.md) and [enums](enum.md) have their own doc # Explicitly specifying data types -In some cases, your .NET property type can be mapped to several PostgreSQL data types; a good example is a `string`, which will be mapped to `text` by default, but can also be mapped to `jsonb`. You can explicitly specify the PostgreSQL data type by adding the following to your model's `OnModelCreating`: +In some cases, your .NET property type can be mapped to several PostgreSQL data types; a good example is a `string`, which will be mapped to `text` by default, but can also be mapped to `jsonb`. You can use either Data Annotation attributes or the Fluent API to configure the PostgreSQL data type: -```c# -builder.Entity() - .Property(b => b.SomeStringProperty) - .HasColumnType("jsonb"); -``` +## [Data Annotations](#tab/data-annotations) Or, if you prefer annotations, use a `ColumnAttribute`: @@ -36,6 +32,16 @@ Or, if you prefer annotations, use a `ColumnAttribute`: public string SomeStringProperty { get; set; } ``` +## [Fluent API](#tab/fluent-api) + +```c# +builder.Entity() + .Property(b => b.SomeStringProperty) + .HasColumnType("jsonb"); +``` + +*** + ## Operation translation to SQL Entity Framework Core allows providers to translate query expressions to SQL for database evaluation. For example, PostgreSQL supports [regular expression operations](http://www.postgresql.org/docs/current/static/functions-matching.html#FUNCTIONS-POSIX-REGEXP), and the Npgsql EF Core provider automatically translates .NET's `Regex.IsMatch()` to use this feature. Since evaluation happens at the server, table data doesn't need to be transferred to the client (saving bandwidth), and in some cases indexes can be used to speed things up. The same C# code on other providers will trigger client evaluation. diff --git a/docs/mapping/json.md b/docs/mapping/json.md index 79d85f9971..e3355ec799 100644 --- a/docs/mapping/json.md +++ b/docs/mapping/json.md @@ -16,7 +16,7 @@ The Npgsql EF Core provider allows you to map PostgreSQL JSON columns in three d The simplest form of mapping to JSON is via a regular string property, just like an ordinary text column: -# [Data Annotations](#tab/data-annotations) +### [Data Annotations](#tab/data-annotations) ```c# public class SomeEntity @@ -27,7 +27,7 @@ public class SomeEntity } ``` -# [Fluent API](#tab/fluent-api) +### [Fluent API](#tab/fluent-api) ```c# class MyContext : DbContext From 57728164633429e02e9b27e4ca1fa601c3416a81 Mon Sep 17 00:00:00 2001 From: Han Verstraete Date: Tue, 7 Jan 2020 14:13:51 +0100 Subject: [PATCH 010/207] Fix typo in configuration example --- docs/modeling/table-column-naming.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/modeling/table-column-naming.md b/docs/modeling/table-column-naming.md index 3f05cabcd5..264b535519 100644 --- a/docs/modeling/table-column-naming.md +++ b/docs/modeling/table-column-naming.md @@ -8,7 +8,7 @@ Starting with 3.0.0, you can use the [EFCore.NamingConventions](https://github.c protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) => optionsBuilder .UseNpgsql(...) - .UseSnakeCaseNamingConventions(); + .UseSnakeCaseNamingConvention(); public class Customer { public int Id { get; set; } From 09fecf5084b6d3aeec83ef4a157cc39a0dad8f72 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Tue, 7 Jan 2020 14:43:43 +0100 Subject: [PATCH 011/207] Remove accidental text --- docs/mapping/general.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/docs/mapping/general.md b/docs/mapping/general.md index acca824aaf..a9415d4d4b 100644 --- a/docs/mapping/general.md +++ b/docs/mapping/general.md @@ -25,8 +25,6 @@ In some cases, your .NET property type can be mapped to several PostgreSQL data ## [Data Annotations](#tab/data-annotations) -Or, if you prefer annotations, use a `ColumnAttribute`: - ```c# [Column(TypeName="jsonb")] public string SomeStringProperty { get; set; } From cf600a7478382787a9cba63175e0b66a9a02ae9c Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Wed, 29 Jan 2020 23:05:41 +0100 Subject: [PATCH 012/207] Document identity sequence options And other tweaks --- docs/modeling/generated-properties.md | 31 ++++++++++++++++++++++++--- 1 file changed, 28 insertions(+), 3 deletions(-) diff --git a/docs/modeling/generated-properties.md b/docs/modeling/generated-properties.md index bea8e08359..28118d96d8 100644 --- a/docs/modeling/generated-properties.md +++ b/docs/modeling/generated-properties.md @@ -6,7 +6,7 @@ > [!NOTE] > It's recommended that you start by reading the general [Entity Framework Core docs on generated properties](https://docs.microsoft.com/en-us/ef/core/modeling/generated-properties). -## Serial and identity columns (auto-increment) +## Identity and serial columns (auto-increment) ### Introduction @@ -22,7 +22,9 @@ The Npgsql EF Core provider allows you to choose which of the above you want on Prior to version 3.0, the Npgsql provider generates "serial" columns for ID columns; starting with version 3.0, it generates "identity by default" instead. In other words, when `ValueGeneratedOnAdd` is specified on a `short`, `int` or `long` property, the Npgsql provider will automatically map it to a serial or identity column. Note that EF Core will automatically recognize key properties by convention (e.g. a property called `Id` in your entity) and will implicitly set them to `ValueGeneratedOnAdd`; a standard model with ID columns should automatically get created with the appropriate column type. > [!CAUTION] -> Since the default strategy has changed, if you have an existing database with migrations, the the first migration created after upgrading to version 3.0 will alter your tables and convert serial columns to identity ones. This is a sensitive, one-time migration operation that should be done with care, and carefully tested before deployment to production. Changing a value generation is a significant change to an existing database. +> Since the default strategy has changed, if you have an existing database with migrations, the the first migration created after upgrading to version 3.0 will alter your tables and convert serial columns to identity ones. This is a sensitive, one-time migration operation that should be done with care, and carefully tested before deployment to production. Changing a value generation strategy is a significant change to an existing database. + +### Defining the default strategy for the entire moel You can easily control the value generation strategy for the entire model. For example, to opt out of the change to identity columns, simply place the following in your context's `OnModelCreating()`: @@ -38,9 +40,32 @@ protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) => optionsBuilder.UseNpgsql("...", o => o.SetPostgresVersion(9, 6)); ``` +### Defining the strategy for a single property + +Regardless of the model default, you can define a value-generation strategy on a property-by-property basis: + +```c# +protected override void OnModelCreating(ModelBuilder modelBuilder) + => modelBuilder.Entity().Property(b => b.Id).UseIdentityAlwaysColumn(); +``` + +### Identity sequence options + +Identity columns have a standard sequence, managed behind the scenes by PostgreSQL; you can customize the sequence options for these. For example, the following makes the column values start at 100: + +```c# +protected override void OnModelCreating(ModelBuilder modelBuilder) + => modelBuilder.Entity().Property(b => b.Id) + .HasIdentityOptions(startValue: 100); +``` + +This can be especially useful when seeding data. Seeded data must explicitly specify all columns - including database-generated ones - but the backing sequence for identity columns isn't aware that the values are in use, and will generate conflicting values. This technique allows to start your identity sequence at a value higher than all seeded data values. Another strategy is to seed negative values only, allowing your identity column to start at 1. + +It is not possible to specify sequence options for serial columns, but you can set up a sequence separately and configure the column's default value (see [sequence-driven columns](#standard-sequence-driven-columns)). + ## Standard sequence-driven columns -While `serial` sets up a sequence for you, you may want to manage sequence creation yourself. This can be useful for cases where you need to control the sequence's increment value (i.e. increment by 2), populate two columns from the same sequence, etc. Adding a sequence to your model is described in [the general EF Core documentation](https://docs.microsoft.com/ef/core/modeling/relational/sequences); once the sequence is specified, you can simply set a column's default value to extract the next value from that sequence. Note that the SQL used to fetch the next value from a sequence differs across databases (see [the PostgreSQL docs](https://www.postgresql.org/docs/current/static/functions-sequence.html)). Your models' `OnModelCreating` should look like this: +While identity and serial columns set up a sequence for you behind the scenes, sometimes you may want to manage sequence creation yourself. For example, you may want to have multiple columns drawing their default values from a single sequence. Adding a sequence to your model is described in [the general EF Core documentation](https://docs.microsoft.com/ef/core/modeling/relational/sequences); once the sequence is specified, you can simply set a column's default value to extract the next value from that sequence. Note that the SQL used to fetch the next value from a sequence differs across databases (see [the PostgreSQL docs](https://www.postgresql.org/docs/current/static/functions-sequence.html)). Your models' `OnModelCreating` should look like this: ```c# protected override void OnModelCreating(ModelBuilder modelBuilder) From f54e74b433d40550dafe3d287790803a5bcbb21b Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Fri, 14 Feb 2020 13:39:11 +0100 Subject: [PATCH 013/207] Update note on generated properties --- docs/modeling/generated-properties.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/modeling/generated-properties.md b/docs/modeling/generated-properties.md index 28118d96d8..1e19edd77e 100644 --- a/docs/modeling/generated-properties.md +++ b/docs/modeling/generated-properties.md @@ -119,9 +119,9 @@ See [the PostgreSQL docs on UUID for more details](https://www.postgresql.org/do ## Computed Columns (On Add or Update) > [!NOTE] -> This feature was introduced in 3.0.0. +> This feature works only on PostgreSQL 12 or above, and was introduced in version 3.0.0 of the provider. -The upcoming PostgreSQL 12 is adding support for [stored generated columns](https://www.postgresql.org/docs/12/ddl-generated-columns.html), and Npgsql feature supports that feature as well. The following configuration: +PostgreSQL 12 added support for [stored generated columns](https://www.postgresql.org/docs/12/ddl-generated-columns.html), and Npgsql feature supports that feature as well. The following configuration: ```c# protected override void OnModelCreating(ModelBuilder modelBuilder) From 42b10381d538a0aaf6f5b683c1653cd8d6e31746 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Fri, 14 Feb 2020 13:58:53 +0100 Subject: [PATCH 014/207] Remove empty line --- docs/mapping/json.md | 1 - 1 file changed, 1 deletion(-) diff --git a/docs/mapping/json.md b/docs/mapping/json.md index e3355ec799..d9e6442fad 100644 --- a/docs/mapping/json.md +++ b/docs/mapping/json.md @@ -11,7 +11,6 @@ The Npgsql EF Core provider allows you to map PostgreSQL JSON columns in three d > [!NOTE] > Mapping to POCO or to System.Text.Json types was introduced in version 3.0.0 - ## String mapping The simplest form of mapping to JSON is via a regular string property, just like an ordinary text column: From 6041f93e552b03f5390d0e1897b1c50d7a029388 Mon Sep 17 00:00:00 2001 From: Sombrio Date: Thu, 5 Mar 2020 14:54:45 -0300 Subject: [PATCH 015/207] Fixed typo --- docs/modeling/generated-properties.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/modeling/generated-properties.md b/docs/modeling/generated-properties.md index 1e19edd77e..900f1c0f7d 100644 --- a/docs/modeling/generated-properties.md +++ b/docs/modeling/generated-properties.md @@ -24,7 +24,7 @@ Prior to version 3.0, the Npgsql provider generates "serial" columns for ID colu > [!CAUTION] > Since the default strategy has changed, if you have an existing database with migrations, the the first migration created after upgrading to version 3.0 will alter your tables and convert serial columns to identity ones. This is a sensitive, one-time migration operation that should be done with care, and carefully tested before deployment to production. Changing a value generation strategy is a significant change to an existing database. -### Defining the default strategy for the entire moel +### Defining the default strategy for the entire model You can easily control the value generation strategy for the entire model. For example, to opt out of the change to identity columns, simply place the following in your context's `OnModelCreating()`: @@ -138,4 +138,4 @@ Will cause the following migration SQL to be generated ALTER TABLE ""Person"" ADD ""DisplayName"" text GENERATED ALWAYS AS (""FirstName"" || ' ' || ""LastName"") STORED; ``` -Note that this is a *stored* column - it is computed once when the row is updated, and takes space on disk. Virtual computed columns, which are computed on each select, are not yet supported by PostgreSQL. \ No newline at end of file +Note that this is a *stored* column - it is computed once when the row is updated, and takes space on disk. Virtual computed columns, which are computed on each select, are not yet supported by PostgreSQL. From 4d57f3ebbce48205b824e1fe49647628b11c7c9f Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Thu, 26 Mar 2020 17:02:40 +0100 Subject: [PATCH 016/207] Add note on xmin as a shadow property --- docs/modeling/concurrency.md | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/docs/modeling/concurrency.md b/docs/modeling/concurrency.md index c43a3cd025..e2c16a2b51 100644 --- a/docs/modeling/concurrency.md +++ b/docs/modeling/concurrency.md @@ -16,3 +16,12 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) => modelBuilder.Entity() .UseXminAsConcurrencyToken(); ``` + +Note that by default, this will set up a [shadow property](https://docs.microsoft.com/en-us/ef/core/modeling/shadow-properties) called `xmin` on your entity. This means that when you load an entity from the database, the value of `xmin` will be stored in the context, making it impossible to use that instance with another context (without reloading the entity). If you plan to pass instances between different contexts, consider adding an `xmin` property of type `uint` on your entity; this will automatically cause the concurrency token to be stored on the instance instead: + +```c# +class Blog +{ + ... + public uint xmin { get; set; } +} \ No newline at end of file From b6704d249526591fd7e4ec5e02f3fa20d6a1c1b2 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Fri, 24 Apr 2020 17:10:26 +0200 Subject: [PATCH 017/207] Fix headings in NTS page --- docs/mapping/nts.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/mapping/nts.md b/docs/mapping/nts.md index 498aa9a847..04ca5d952d 100644 --- a/docs/mapping/nts.md +++ b/docs/mapping/nts.md @@ -1,4 +1,4 @@ -## Spatial Mapping with NetTopologySuite +# Spatial Mapping with NetTopologySuite > [!NOTE] > It's recommended that you start by reading the general [Entity Framework Core docs on spatial support](https://docs.microsoft.com/ef/core/modeling/spatial). @@ -7,7 +7,7 @@ PostgreSQL supports spatial data and operations via [the PostGIS extension](http Note that the EF Core NetTopologySuite plugin depends on [the Npgsql ADO.NET NetTopology plugin](http://www.npgsql.org/doc/types/nts.html), which provides NetTopologySuite support at the lower level. The EF Core plugin automatically arranged for the ADO.NET plugin to be set up. -# Setup +## Setup To set up the NetTopologySuite plugin, add the [Npgsql.EntityFrameworkCore.PostgreSQL.NetTopologySuite nuget](https://www.nuget.org/packages/Npgsql.EntityFrameworkCore.PostgreSQL.NetTopologySuite) to your project. Then, make the following modification to your `UseNpgsql()` line: From 573ac4b26d6bd9225dd44a356159270bbe7f49a2 Mon Sep 17 00:00:00 2001 From: Rawr Date: Sat, 25 Apr 2020 15:17:50 -0500 Subject: [PATCH 018/207] Added example of `.Matches` taking a `ToTsQuery` --- docs/mapping/full-text-search.md | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/docs/mapping/full-text-search.md b/docs/mapping/full-text-search.md index 2234706bfd..e067eb41bf 100644 --- a/docs/mapping/full-text-search.md +++ b/docs/mapping/full-text-search.md @@ -19,14 +19,15 @@ public class BlogPost Almost all PostgreSQL full text search functions can be called through LINQ queries. All supported EF Core LINQ methods are defined in extension classes in the `Microsoft.EntityFrameworkCore` namespace, so simply referencing the Npgsql provider will light up these methods. Here is a table showing translations for some operations; if an operation you need is missing, please open an issue to request for it. -| This C# expression... | ... gets translated to this SQL | -|----------------------------------------------------------|---------------------------------------------------------------------| -| .Select(c => EF.Functions.ToTsVector("english", c.Name)) | [SELECT to_tsvector('english'::regconfig, c."Name")](https://www.postgresql.org/docs/current/static/textsearch-controls.html#TEXTSEARCH-PARSING-DOCUMENTS) -| .Select(c => NpgsqlTsVector.Parse("b")) | [SELECT CAST('b' AS tsvector)](https://www.postgresql.org/docs/current/static/sql-expressions.html#SQL-SYNTAX-TYPE-CASTS) -| .Select(c => EF.Functions.ToTsQuery("english", "pgsql")) | [SELECT to_tsquery('english'::regconfig, 'pgsql')`](https://www.postgresql.org/docs/current/static/textsearch-controls.html#TEXTSEARCH-PARSING-QUERIES) -| .Select(c => NpgsqlTsQuery.Parse("b")) | [SELECT CAST('b' AS tsquery)](https://www.postgresql.org/docs/current/static/sql-expressions.html#SQL-SYNTAX-TYPE-CASTS) -| .Where(c => c.SearchVector.Matches("Npgsql")) | [WHERE c."SearchVector" @@ 'Npgsql'](https://www.postgresql.org/docs/current/static/textsearch-intro.html#TEXTSEARCH-MATCHING) -| .Select(c => EF.Functions.ToTsQuery(c.SearchQuery).ToNegative()) | [SELECT !! to_tsquery(c."SearchQuery")](https://www.postgresql.org/docs/current/static/textsearch-features.html#TEXTSEARCH-MANIPULATE-TSQUERY) +| This C# expression... | ... gets translated to this SQL | +|----------------------------------------------------------------------------------|---------------------------------------------------------------------| +| .Select(c => EF.Functions.ToTsVector("english", c.Name)) | [SELECT to_tsvector('english'::regconfig, c."Name")](https://www.postgresql.org/docs/current/static/textsearch-controls.html#TEXTSEARCH-PARSING-DOCUMENTS) +| .Select(c => NpgsqlTsVector.Parse("b")) | [SELECT CAST('b' AS tsvector)](https://www.postgresql.org/docs/current/static/sql-expressions.html#SQL-SYNTAX-TYPE-CASTS) +| .Select(c => EF.Functions.ToTsQuery("english", "pgsql")) | [SELECT to_tsquery('english'::regconfig, 'pgsql')`](https://www.postgresql.org/docs/current/static/textsearch-controls.html#TEXTSEARCH-PARSING-QUERIES) +| .Select(c => NpgsqlTsQuery.Parse("b")) | [SELECT CAST('b' AS tsquery)](https://www.postgresql.org/docs/current/static/sql-expressions.html#SQL-SYNTAX-TYPE-CASTS) +| .Where(c => c.SearchVector.Matches("Npgsql")) | [WHERE c."SearchVector" @@ 'Npgsql'](https://www.postgresql.org/docs/current/static/textsearch-intro.html#TEXTSEARCH-MATCHING) +| .Where(c => c.SearchVector.Matches(EF.Functions.ToTsQuery("Npgsql"))) | [WHERE c."TsVector" @@ to_tsquery('Npgsql')](https://www.postgresql.org/docs/current/static/textsearch-controls.html#TEXTSEARCH-PARSING-QUERIES) +| .Select(c => EF.Functions.ToTsQuery(c.SearchQuery).ToNegative()) | [SELECT !! to_tsquery(c."SearchQuery")](https://www.postgresql.org/docs/current/static/textsearch-features.html#TEXTSEARCH-MANIPULATE-TSQUERY) | .Select(c => EF.Functions.ToTsVector(c.Name).SetWeight(NpgsqlTsVector.Lexeme.Weight.A)) | [SELECT setweight(to_tsvector(c."Name"), 'A')](https://www.postgresql.org/docs/current/static/textsearch-features.html#TEXTSEARCH-MANIPULATE-TSVECTOR) ## Setting up and querying a full text search index on an entity From c5a4757e1f33c485b1c7e926ecae6e2a5764a4c0 Mon Sep 17 00:00:00 2001 From: Rawr Date: Sun, 26 Apr 2020 08:25:04 -0500 Subject: [PATCH 019/207] Added `.OrderByDescending` `Rank` example MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Could possibly drop the `.Where` ¯\_(ツ)_/¯ --- docs/mapping/full-text-search.md | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/docs/mapping/full-text-search.md b/docs/mapping/full-text-search.md index e067eb41bf..92d473930d 100644 --- a/docs/mapping/full-text-search.md +++ b/docs/mapping/full-text-search.md @@ -19,16 +19,18 @@ public class BlogPost Almost all PostgreSQL full text search functions can be called through LINQ queries. All supported EF Core LINQ methods are defined in extension classes in the `Microsoft.EntityFrameworkCore` namespace, so simply referencing the Npgsql provider will light up these methods. Here is a table showing translations for some operations; if an operation you need is missing, please open an issue to request for it. -| This C# expression... | ... gets translated to this SQL | -|----------------------------------------------------------------------------------|---------------------------------------------------------------------| -| .Select(c => EF.Functions.ToTsVector("english", c.Name)) | [SELECT to_tsvector('english'::regconfig, c."Name")](https://www.postgresql.org/docs/current/static/textsearch-controls.html#TEXTSEARCH-PARSING-DOCUMENTS) -| .Select(c => NpgsqlTsVector.Parse("b")) | [SELECT CAST('b' AS tsvector)](https://www.postgresql.org/docs/current/static/sql-expressions.html#SQL-SYNTAX-TYPE-CASTS) -| .Select(c => EF.Functions.ToTsQuery("english", "pgsql")) | [SELECT to_tsquery('english'::regconfig, 'pgsql')`](https://www.postgresql.org/docs/current/static/textsearch-controls.html#TEXTSEARCH-PARSING-QUERIES) -| .Select(c => NpgsqlTsQuery.Parse("b")) | [SELECT CAST('b' AS tsquery)](https://www.postgresql.org/docs/current/static/sql-expressions.html#SQL-SYNTAX-TYPE-CASTS) -| .Where(c => c.SearchVector.Matches("Npgsql")) | [WHERE c."SearchVector" @@ 'Npgsql'](https://www.postgresql.org/docs/current/static/textsearch-intro.html#TEXTSEARCH-MATCHING) -| .Where(c => c.SearchVector.Matches(EF.Functions.ToTsQuery("Npgsql"))) | [WHERE c."TsVector" @@ to_tsquery('Npgsql')](https://www.postgresql.org/docs/current/static/textsearch-controls.html#TEXTSEARCH-PARSING-QUERIES) -| .Select(c => EF.Functions.ToTsQuery(c.SearchQuery).ToNegative()) | [SELECT !! to_tsquery(c."SearchQuery")](https://www.postgresql.org/docs/current/static/textsearch-features.html#TEXTSEARCH-MANIPULATE-TSQUERY) +| This C# expression... | ... gets translated to this SQL | +|-----------------------------------------------------------------------------------------|---------------------------------------------------------------------| +| .Select(c => EF.Functions.ToTsVector("english", c.Name)) | [SELECT to_tsvector('english'::regconfig, c."Name")](https://www.postgresql.org/docs/current/static/textsearch-controls.html#TEXTSEARCH-PARSING-DOCUMENTS) +| .Select(c => NpgsqlTsVector.Parse("b")) | [SELECT CAST('b' AS tsvector)](https://www.postgresql.org/docs/current/static/sql-expressions.html#SQL-SYNTAX-TYPE-CASTS) +| .Select(c => EF.Functions.ToTsQuery("english", "pgsql")) | [SELECT to_tsquery('english'::regconfig, 'pgsql')`](https://www.postgresql.org/docs/current/static/textsearch-controls.html#TEXTSEARCH-PARSING-QUERIES) +| .Select(c => NpgsqlTsQuery.Parse("b")) | [SELECT CAST('b' AS tsquery)](https://www.postgresql.org/docs/current/static/sql-expressions.html#SQL-SYNTAX-TYPE-CASTS) +| .Where(c => c.SearchVector.Matches("Npgsql")) | [WHERE c."SearchVector" @@ 'Npgsql'](https://www.postgresql.org/docs/current/static/textsearch-intro.html#TEXTSEARCH-MATCHING) +| .Where(c => c.SearchVector.Matches(EF.Functions.ToTsQuery("Npgsql"))) | [WHERE c."SearchVector" @@ to_tsquery('Npgsql')](https://www.postgresql.org/docs/current/static/textsearch-controls.html#TEXTSEARCH-PARSING-QUERIES) +| .Select(c => EF.Functions.ToTsQuery(c.SearchQuery).ToNegative()) | [SELECT !! to_tsquery(c."SearchQuery")](https://www.postgresql.org/docs/current/static/textsearch-features.html#TEXTSEARCH-MANIPULATE-TSQUERY) | .Select(c => EF.Functions.ToTsVector(c.Name).SetWeight(NpgsqlTsVector.Lexeme.Weight.A)) | [SELECT setweight(to_tsvector(c."Name"), 'A')](https://www.postgresql.org/docs/current/static/textsearch-features.html#TEXTSEARCH-MANIPULATE-TSVECTOR) +| .Where(c => c.SearchVector.Matches(EF.Functions.ToTsQuery("Npgsql")))
.OrderByDescending(c => c.SearchVector.Rank(EF.Functions.ToTsQuery("Npgsql"))) | WHERE (c."SearchVector" @@ to_tsquery('Npgsql'))
ORDER BY ts_rank(c."SearchVector", to_tsquery('Npgsql')) DESC + ## Setting up and querying a full text search index on an entity From 3dc225cdce755380668b758d3d69565709ecf3ba Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Wed, 13 May 2020 09:01:14 +0200 Subject: [PATCH 020/207] Bump version of EFCore.PG in basic sample --- docs/index.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/index.md b/docs/index.md index 33d7b66548..a7d4da8444 100644 --- a/docs/index.md +++ b/docs/index.md @@ -23,7 +23,7 @@ Below is a `.csproj` file for a console application that uses the Npgsql EF Core netcoreapp3.0 - + ``` From b926e4ab373b8c7ec061cb9e70099095442e2bff Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Wed, 13 May 2020 15:44:33 +0200 Subject: [PATCH 021/207] Update badges --- docs/index.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/docs/index.md b/docs/index.md index a7d4da8444..b43fb027e2 100644 --- a/docs/index.md +++ b/docs/index.md @@ -1,8 +1,7 @@ [![stable](https://img.shields.io/nuget/v/Npgsql.EntityFrameworkCore.PostgreSQL.svg?label=stable)](https://www.nuget.org/packages/Npgsql.EntityFrameworkCore.PostgreSQL/) [![unstable](https://img.shields.io/myget/npgsql-unstable/vpre/Npgsql.EntityFrameworkCore.PostgreSQL.svg?label=unstable)](https://www.myget.org/feed/npgsql-unstable/package/nuget/Npgsql.EntityFrameworkCore.PostgreSQL) [![next patch](https://img.shields.io/myget/npgsql/v/Npgsql.EntityFrameworkCore.PostgreSQL.svg?label=next%20patch)](https://www.myget.org/feed/npgsql/package/nuget/Npgsql.EntityFrameworkCore.PostgreSQL) -[![appveyor](https://img.shields.io/appveyor/ci/roji/npgsql-entityframeworkcore-postgresql/dev.svg?label=appveyor)](https://ci.appveyor.com/project/roji/npgsql-entityframeworkcore-postgresql) -[![travis](https://img.shields.io/travis/npgsql/npgsql.svg?label=travis)](https://travis-ci.org/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL) +[![build](https://img.shields.io/github/workflow/status/efcore.pg/npgsql/Build)](https://github.com/npgsql/efcore.pg/actions) [![gitter](https://img.shields.io/badge/gitter-join%20chat-brightgreen.svg)](https://gitter.im/npgsql/npgsql) # Getting Started From 4b912c0cb77b28b8fe3417b99e63cdeeb876db2f Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Tue, 26 May 2020 00:25:59 +0200 Subject: [PATCH 022/207] Correct JsonTypeof sample --- docs/mapping/json.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/mapping/json.md b/docs/mapping/json.md index d9e6442fad..ee187cd8e9 100644 --- a/docs/mapping/json.md +++ b/docs/mapping/json.md @@ -208,7 +208,7 @@ The following expression types and functions are translated: | `.Where(e => EF.Functions.JsonExists(e.Customer, "Age")` | [`WHERE "Customer" ? 'Age'`](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) | `.Where(e => EF.Functions.JsonExistsAny(e.Customer, "Age", "Address")` | [`WHERE "Customer" ?\| ARRAY['Age','Address']`](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) | `.Where(e => EF.Functions.JsonExistsAll(e.Customer, "Age", "Address")` | [`WHERE "Customer" ?& ARRAY['Age','Address']`](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) -| `.Where(e => EF.Functions.JsonTypeof(e.Customer.Age)` | [`WHERE jsonb_typeof("Customer"->'Age')`](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-PROCESSING-TABLE) +| `.Where(e => EF.Functions.JsonTypeof(e.Customer.Age) == "number")` | [`WHERE jsonb_typeof("Customer"->'Age') = 'number'`](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-PROCESSING-TABLE) # [JsonDocument Mapping](#tab/jsondocument) @@ -222,7 +222,7 @@ The following expression types and functions are translated: | `.Where(e => EF.Functions.JsonExists(e.Customer, "Age")` | [`WHERE "Customer" ? 'Age'`](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) | `.Where(e => EF.Functions.JsonExistsAny(e.Customer, "Age", "Address")` | [`WHERE "Customer" ?\| ARRAY['Age','Address']`](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) | `.Where(e => EF.Functions.JsonExistsAll(e.Customer, "Age", "Address")` | [`WHERE "Customer" ?& ARRAY['Age','Address']`](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) -| `.Where(e => EF.Functions.JsonTypeof(e.Customer.GetProperty("Age"))` | [`WHERE jsonb_typeof("Customer"->'Age')`](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-PROCESSING-TABLE) +| `.Where(e => EF.Functions.JsonTypeof(e.Customer.GetProperty("Age") == "number")` | [`WHERE jsonb_typeof("Customer"->'Age') = 'number'`](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-PROCESSING-TABLE) *** From 1b60f385ea5a0c0b164d2d142763a6bc01780097 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Thu, 11 Jun 2020 19:06:53 +0200 Subject: [PATCH 023/207] Document collation and case sensitivity --- docs/misc/collations-and-case-sensitivity.md | 107 +++++++++++++++++++ docs/misc/database-creation.md | 36 +++++++ docs/{miscellaneous.md => misc/other.md} | 47 +------- docs/toc.md | 5 +- 4 files changed, 152 insertions(+), 43 deletions(-) create mode 100644 docs/misc/collations-and-case-sensitivity.md create mode 100644 docs/misc/database-creation.md rename docs/{miscellaneous.md => misc/other.md} (61%) diff --git a/docs/misc/collations-and-case-sensitivity.md b/docs/misc/collations-and-case-sensitivity.md new file mode 100644 index 0000000000..03f0ed1166 --- /dev/null +++ b/docs/misc/collations-and-case-sensitivity.md @@ -0,0 +1,107 @@ +# Collations and Case Sensitivity + +> [!NOTE] +> This feature is introduced in EF Core 5.0. +> +> It's recommended that you start by reading [the general Entity Framework Core docs on collations and case sensitivity](https://docs.microsoft.com/ef/core/miscellaneous/collations-and-case-sensitivity). + +PostgreSQL is a case-sensitive database by default, but provides various possibilities for performing case-insensitive operations and working with collations. Unfortunately, full collation support is recent and somewhat incomplete, so you may need to carefully review your options below and pick the one which suits you. + +## PostgreSQL collations + +While PostgreSQL has supported collations for a long time, supported was limited to "deterministic" collations, which did not allow for case-insensitive or accent-insensitive operations. PostgreSQL 12 introduced non-deterministic ICU collations, so it is now possible to use collations in a more flexible way. Read more about PostgreSQL collation support [in the documentation](https://www.postgresql.org/docs/current/collation.html). + +> [!NOTE] +> It is not yet possible to use pattern matching operators such as LIKE on columns with a non-deterministic collation. + +### Creating a collation + +In PostgreSQL, collations are first-class, named database objects which can be created and dropped, just like tables. To create a collation, place the following in your context's `OnModelCreating`: + +```c# +modelBuilder.HasCollation("my_collation", locale: "en-u-ks-primary", provider: "icu", deterministic: false); +``` + +This creates a collation with the name `some_collation`: this is an arbitrary name you can choose, which you will be specifying later when assigning the collation to columns. The rest of the parameters instruct PostgreSQL to create a non-deterministic, case-insensitive ICU collation. ICU collations are very powerful, and allow you to specify precise rules with regards to case, accents and other textual aspects. Consult [the ICU docs](http://userguide.icu-project.org/collation) for more information on supported features and keywords. + +### Column collation + +Once a collation has been created in your database, you can specify it on columns: + +```c# +protected override void OnModelCreating(ModelBuilder modelBuilder) +{ + modelBuilder.HasCollation("my_collation", locale: "en-u-ks-primary", provider: "icu", deterministic: false); + + modelBuilder.Entity().Property(c => c.Name) + .UseCollation("my_collation"); +} +``` + +This will cause all textual operators on this column to be case-insensitive. + +### Database collation + +PostgreSQL also allows you to specify collations at the database level, when it is created. While this will eventually allow specifying that all columns and operations are case-insensitive, for example, PostgreSQL currently does not support non-deterministic collations at the database level. To work around this limitation, the EF Core provider has a feature which allows you to specify the `default column collation` at the model level, and the provider will ensure it is automatically specified on all columns: + +```c# +protected override void OnModelCreating(ModelBuilder modelBuilder) +{ + modelBuilder.HasCollation("my_collation", locale: "en-u-ks-primary", provider: "icu", deterministic: false); + + builder.UseDefaultColumnCollation("my_collation"); +} +``` + +All columns created after this directive is added will automatically have their collation specified accordingly, and all existing columns will be altered. The end result of the above is very similar to specifying a database collation: instead of telling PostgreSQL to implicit apply a collation to all columns, the EF Core provider does the same. + +## The citext type + +The older PostgreSQL method for performing case-insensitive text operations is the `citext` type; it is similar to the `text` type, but operators are functions between `citext` values are implicitly case-insensitive. [The PostgreSQL docs](https://www.postgresql.org/docs/current/citext.html) provide more information on this type. + +`citext` is available in a PostgreSQL-bundled extension, so you'll first have to install it: + +```c# +modelBuilder.HasPostgresExtension("citext"); +``` + +Specifying that a column should use `citext` is simply a matter of setting the column's type: + +### [Data Annotations](#tab/data-annotations) + +```c# +public class Blog +{ + public int Id { get; set; } + [Column(TypeName = "citext")] + public string Name { get; set; } +} +``` + +### [Fluent API](#tab/fluent-api) + +```c# +protected override void OnModelCreating(ModelBuilder modelBuilder) +{ + modelBuilder.Entity().Property(b => b.Name) + .HasColumnType("citext"); +} +``` + +*** + +Some limitations (others are listed in [the PostgreSQL docs](https://www.postgresql.org/docs/current/citext.html)): + +* While `citext` allows case-insensitive comparisons, it doesn't handle other aspects of collations, such as accents. +* Several PostgreSQL text functions are overloaded to work with `citext` as expected, but others aren't. Using a function that isn't overloaded will result in a regular, case-sensitive match. +* Unlike collations, `citext` does not allow the same column to be compared case-sensitively in some queries, and and insensitively in others. + +## ILIKE + +`ILIKE` is a PostgreSQL-specific operator that works just like `LIKE`, but is case-insensitive. If you only need to perform case-insensitive `LIKE` pattern matching, then this could be sufficient. The provider exposes this via `EF.Functions.ILike`: + +```c# +var results = ctx.Blogs + .Where(b => EF.Functions.ILike(b.Name, "a%b")) + .ToList(); +``` diff --git a/docs/misc/database-creation.md b/docs/misc/database-creation.md new file mode 100644 index 0000000000..63a6a89e2e --- /dev/null +++ b/docs/misc/database-creation.md @@ -0,0 +1,36 @@ +# Database Creation + +## Specifying the administrative db + +When the Npgsql EF Core provider creates or deletes a database (`EnsureCreated()`, `EnsureDeleted()`), it must connect to an administrative database which already exists (with PostgreSQL you always have to be connected to some database, even when creating/deleting another database). Up to now the `postgres` database was used, which is supposed to always be present. + +However, there are some PostgreSQL-like databases where the `postgres` database is not available. For these cases you can specify the administrative database as follows: + +```c# +protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) + => optionsBuilder.UseNpgsql( + "", + options => options.UseAdminDatabase("my_admin_db")); +``` + +## Using a database template + +When creating a new database, +[PostgreSQL allows specifying another "template database"](http://www.postgresql.org/docs/current/static/manage-ag-templatedbs.html) +which will be copied as the basis for the new one. This can be useful for including database entities which are not managed by Entity Framework Core. You can trigger this by using `HasDatabaseTemplate` in your context's `OnModelCreating`: + +```c# +protected override void OnModelCreating(ModelBuilder modelBuilder) + => modelBuilder.HasDatabaseTemplate("my_template_db"); +``` + +## Setting a tablespace + +PostgreSQL allows you to locate your database in different parts of your filesystem, [via tablespaces](https://www.postgresql.org/docs/current/static/manage-ag-tablespaces.html). The Npgsql EF Core provider allows you to specify your database's namespace: + +```c# +protected override void OnModelCreating(ModelBuilder modelBuilder) + => modelBuilder.UseTablespace("my_tablespace"); +``` + +You must have created your tablespace prior to this via the `CREATE TABLESPACE` command - the Npgsql EF Core provider does not do this for you. Note also that specifying a tablespace on specific tables is not supported. diff --git a/docs/miscellaneous.md b/docs/misc/other.md similarity index 61% rename from docs/miscellaneous.md rename to docs/misc/other.md index 06f5607951..c9e9038e15 100644 --- a/docs/miscellaneous.md +++ b/docs/misc/other.md @@ -1,4 +1,4 @@ -# Miscellaneous +# Other ## PostgreSQL extensions @@ -23,16 +23,6 @@ protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) This strategy relies on the `IsTransient` property of `NpgsqlException`. Both this property and the retrying strategy are new and should be considered somewhat experimental - please report any issues. -## Comments - -PostgreSQL allows you to [attach comments](https://www.postgresql.org/docs/current/static/sql-syntax-lexical.html#SQL-SYNTAX-COMMENTS) to database objects, which can help explain their purpose for someone examining the schema. The Npgsql EF Core provider supports this for tables or columns, simply set the comment in your model's `OnModelCreating` as follows: - -```c# -protected override void OnModelCreating(ModelBuilder modelBuilder) - => modelBuilder.Entity() - .HasComment("Some comment"); -``` - ## Certificate authentication The Npgsql allows you to provide a callback for verifying the server-provided certificates, and to provide a callback for providing certificates to the server. The latter, if properly set up on the PostgreSQL side, allows you to do client certificate authentication - see [the Npgsql docs](http://www.npgsql.org/doc/security.html#encryption-ssltls) and also [the PostgreSQL docs](https://www.postgresql.org/docs/current/static/ssl-tcp.html#SSL-CLIENT-CERTIFICATES) on setting this up. @@ -52,43 +42,16 @@ protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) You may also consider passing `Trust Server Certificate=true` in your connection string to make Npgsql accept whatever certificate your PostgreSQL provides (useful for self-signed certificates). -## Database Creation - -### Specifying the administrative db - -When the Npgsql EF Core provider creates or deletes a database (`EnsureCreated()`, `EnsureDeleted()`), it must connect to an administrative database which already exists (with PostgreSQL you always have to be connected to some database, even when creating/deleting another database). Up to now the `postgres` database was used, which is supposed to always be present. - -However, there are some PostgreSQL-like databases where the `postgres` database is not available. For these cases you can specify the administrative database as follows: - -```c# -protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) - => optionsBuilder.UseNpgsql( - "", - options => options.UseAdminDatabase("my_admin_db")); -``` - -### Using a database template - -When creating a new database, -[PostgreSQL allows specifying another "template database"](http://www.postgresql.org/docs/current/static/manage-ag-templatedbs.html) -which will be copied as the basis for the new one. This can be useful for including database entities which are not managed by Entity Framework Core. You can trigger this by using `HasDatabaseTemplate` in your context's `OnModelCreating`: - -```c# -protected override void OnModelCreating(ModelBuilder modelBuilder) - => modelBuilder.HasDatabaseTemplate("my_template_db"); -``` - -### Setting a tablespace +## Comments -PostgreSQL allows you to locate your database in different parts of your filesystem, [via tablespaces](https://www.postgresql.org/docs/current/static/manage-ag-tablespaces.html). The Npgsql EF Core provider allows you to specify your database's namespace: +PostgreSQL allows you to [attach comments](https://www.postgresql.org/docs/current/static/sql-syntax-lexical.html#SQL-SYNTAX-COMMENTS) to database objects, which can help explain their purpose for someone examining the schema. The Npgsql EF Core provider supports this for tables or columns, simply set the comment in your model's `OnModelCreating` as follows: ```c# protected override void OnModelCreating(ModelBuilder modelBuilder) - => modelBuilder.UseTablespace("my_tablespace"); + => modelBuilder.Entity() + .HasComment("Some comment"); ``` -You must have created your tablespace prior to this via the `CREATE TABLESPACE` command - the Npgsql EF Core provider does not do this for you. Note also that specifying a tablespace on specific tables is not supported. - ## CockroachDB Interleave In Parent If you're using CockroachDB, the Npgsql EF Core provider exposes its ["interleave in parent" feature](https://www.cockroachlabs.com/docs/stable/interleave-in-parent.html). Use the following code: diff --git a/docs/toc.md b/docs/toc.md index f4885c8ff7..65d73b42bb 100644 --- a/docs/toc.md +++ b/docs/toc.md @@ -19,5 +19,8 @@ ## [Arrays](mapping/array.md) ## [Enums](mapping/enum.md) ## [Ranges](mapping/range.md) -# [Miscellaneous](miscellaneous.md) +# Miscellaneous +## [Collations and Case Sensitivity](misc/collations-and-case-sensitivity.md) +## [Database Creation](misc/database-creation.md) +## [Other](misc/other.md) # [API Reference](../../obj/api/EFCore.PG/) From 6b3f89a60990929e6e58a9610fcacb4009a7d582 Mon Sep 17 00:00:00 2001 From: Kurlaev Nikita Date: Mon, 22 Jun 2020 10:40:17 +0300 Subject: [PATCH 024/207] Fix code fragment Added closing backticks for code fragment --- docs/modeling/concurrency.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/modeling/concurrency.md b/docs/modeling/concurrency.md index e2c16a2b51..81b0116858 100644 --- a/docs/modeling/concurrency.md +++ b/docs/modeling/concurrency.md @@ -24,4 +24,4 @@ class Blog { ... public uint xmin { get; set; } -} \ No newline at end of file +}``` From 6fa3d98eb611af7b7796c34bf7d6e7aaf2fd7232 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Fri, 14 Feb 2020 14:49:32 +0100 Subject: [PATCH 025/207] Update full-text search docs --- docs/mapping/full-text-search.md | 102 ++++++++++++++++++++----------- 1 file changed, 65 insertions(+), 37 deletions(-) diff --git a/docs/mapping/full-text-search.md b/docs/mapping/full-text-search.md index 92d473930d..dd92fe0b3b 100644 --- a/docs/mapping/full-text-search.md +++ b/docs/mapping/full-text-search.md @@ -7,10 +7,11 @@ PostgreSQL has [built-in support for full-text search](https://www.postgresql.or PostgreSQL full text search types are mapped onto .NET types built-in to Npgsql. The `tsvector` type is mapped to `NpgsqlTsVector` and `tsquery` is mapped to `NpgsqlTsQuery`. This means you can use properties of type `NpgsqlTsVector` directly in your model to create `tsvector` columns. The `NpgsqlTsQuery` type on the other hand, is used in LINQ queries. ```c# -public class BlogPost +public class Product { + public int Id { get; set; } public string Title { get; set; } - public string Content { get; set; } + public string Description { get; set; } public NpgsqlTsVector SearchVector { get; set; } } ``` @@ -34,11 +35,11 @@ Almost all PostgreSQL full text search functions can be called through LINQ quer ## Setting up and querying a full text search index on an entity -As [the PostgreSQL documentation](https://www.postgresql.org/docs/current/static/textsearch-tables.html) explains, full-text search requires an index to run efficiently. This section will show two ways to do this, both (currently) requiring raw SQL in your migrations. Read the PostgreSQL docs for more information on the different approaches. +[As the PostgreSQL documentation explains](https://www.postgresql.org/docs/current/static/textsearch-tables.html), full-text search requires an index to run efficiently. This section will show two ways to do this, each having its benefits and drawbacks. Please read the PostgreSQL docs for more information on the two different approaches. -### Method 1: Expression index +### Method 1: tsvector column -The simpler method to use full-text search is to set up an expression index. Let's take the following entity: +This method adds a `tsvector` column to your table, that is automatically updated when the row is modified. First, add an `NpgsqlTsVector` property to your entity: ```c# public class Product @@ -46,48 +47,34 @@ public class Product public int Id { get; set; } public string Name { get; set; } public string Description { get; set; } + public NpgsqlTsVector SearchVector { get; set; } } ``` -Create a migration which will contain the index creation SQL (`dotnet ef migrations add ...`). At this point, open the generated migration with your editor and add the following: - -```c# -protected override void Up(MigrationBuilder migrationBuilder) -{ - migrationBuilder.Sql(@"CREATE INDEX fts_idx ON ""Product"" USING GIN (to_tsvector('english', ""Name"" || ' ' || ""Description""));"); -} - -protected override void Down(MigrationBuilder migrationBuilder) - migrationBuilder.Sql(@"DROP INDEX fts_idx;"); -} -``` - -This will create a full-text search index on the `Name` and `Description` columns. You can query as follows: - -```c# -var context = new ProductDbContext(); -var npgsql = context.Products - .Where(p => EF.Functions.ToTsVector("english", p.Name + " " + p.Description).Matches("Npgsql")) - .ToList(); -``` +Setting up the column to be auto-updated depends on your PostgreSQL version. On PostgreSQL 12 and above, the column can be a simple [generated column](../modeling/generated-properties##computed-columns-on-add-or-update), and version 5.0.0 contains sugar for setting that up. In previous versions, you must manually set up database triggers that update the column instead. -### Method 2: tsvector column +# [PostgreSQL 12+](#tab/pg12) -Instead of an expression index, this method will add a `tsvector` column on your table that updates itself with a trigger. +> [!NOTE] +> The below only works on PostgreSQL 12 and version 5.0.0 of the EF Core provider. -First, add an `NpgsqlTsVector` property to your entity: +The following will set up a generated `tsvector` column, over which you can easily create an index: ```c# -public class Product +protected override void OnModelCreating(ModelBuilder modelBuilder) { - public int Id { get; set; } - public string Name { get; set; } - public string Description { get; set; } - public NpgsqlTsVector SearchVector { get; set; } -} + modelBuilder.Entity() + .HasGeneratedTsVectorColumn( + p => b.TsVector, + "english", // Text search config + p => new { p.Name, p.Description }) // Included properties + .HasIndex(b => b.TsVector) + .HasMethod("GIN"); // Index method on the search vector (GIN or GIST) ``` -and modify the `OnModelCreating()` of your context class to add an index as follows: +# [Older Versions](#tab/pgold) + +First, modify the `OnModelCreating()` of your context class to add an index as follows: ```c# protected override void OnModelCreating(ModelBuilder modelBuilder) @@ -124,7 +111,9 @@ public partial class CreateProductTable : Migration } ``` -Any inserts or updates on the `Products` table will now update the `SearchVector` column and maintain it automatically. You can query it as follows: +*** + +Once your auto-updated `tsvector` column is set up, any inserts or updates on the `Products` table will now update the `SearchVector` column and maintain it automatically. You can query it as follows: ```c# var context = new ProductDbContext(); @@ -132,3 +121,42 @@ var npgsql = context.Products .Where(p => p.SearchVector.Matches("Npgsql")) .ToList(); ``` + +### Method 2: Expression index + +Version 5.0.0 of the provider includes sugar for defining the appropriate expression index; if you're using an older version, you'll have to define a raw SQL migration yourself. + +# [EF Core 5+](#tab/pg12) + +```c# +modelBuilder.Entity() + .HasIndex(b => new { b.Title, b.Description }) + .IsTsVectorExpressionIndex("english"); +``` + +# [Older Versions](#tab/efold) + +Create a migration which will contain the index creation SQL (`dotnet ef migrations add ...`). At this point, open the generated migration with your editor and add the following: + +```c# +protected override void Up(MigrationBuilder migrationBuilder) +{ + migrationBuilder.Sql(@"CREATE INDEX fts_idx ON ""Product"" USING GIN (to_tsvector('english', ""Name"" || ' ' || ""Description""));"); +} + +protected override void Down(MigrationBuilder migrationBuilder) + migrationBuilder.Sql(@"DROP INDEX fts_idx;"); +} +``` + +*** + +Once the index is created on the `Title` and `Description` columns, you can query as follows: + +```c# +var context = new ProductDbContext(); +var npgsql = context.Products + .Where(p => EF.Functions.ToTsVector("english", p.Title + " " + p.Description) + .Matches("Npgsql")) + .ToList(); +``` From 2f2e7cda238a2a9616fc37030db348693b68c081 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Sat, 18 Jul 2020 17:05:04 +0300 Subject: [PATCH 026/207] Note to call ReloadTypes after Migrate() --- docs/mapping/enum.md | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/docs/mapping/enum.md b/docs/mapping/enum.md index 3a940544bd..5fbc0b0822 100644 --- a/docs/mapping/enum.md +++ b/docs/mapping/enum.md @@ -23,10 +23,21 @@ protected override void OnModelCreating(ModelBuilder builder) ``` --- -
This causes the EF Core provider to create your data enum type, `Mood`, with two labels: `happy` and `sad`. This will cause the appropriate migration to be created. +If you are using `context.Database.Migrate()` to create your enums, you need to instruct Npgsql to reload all types after applying your migrations: + +```c# +context.Database.Migrate(); + +using (var conn = (NpgsqlConnection)context.Database.GetDbConnection()) +{ + conn.Open(); + conn.ReloadTypes(); +} +``` + ## Mapping your enum Even if your database enum is created, Npgsql has to know about it, and especially about your CLR enum type that should be mapped to it. This is done by adding the following code, *before* any EF Core operations take place. An appropriate place for this is in the static constructor on your DbContext class: From 01255baaf1ace1a7427aee63a48e54828218661c Mon Sep 17 00:00:00 2001 From: Boris Wilhelms Date: Wed, 2 Sep 2020 08:55:32 +0200 Subject: [PATCH 027/207] Update concurrency.md Adds missing code block end "tags" --- docs/modeling/concurrency.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/modeling/concurrency.md b/docs/modeling/concurrency.md index 81b0116858..f01a7b40b6 100644 --- a/docs/modeling/concurrency.md +++ b/docs/modeling/concurrency.md @@ -24,4 +24,5 @@ class Blog { ... public uint xmin { get; set; } -}``` +} +``` From f576d0acd661451789d26bd72bfb0f6b413a7f51 Mon Sep 17 00:00:00 2001 From: Brar Piening Date: Wed, 2 Sep 2020 18:19:24 +0200 Subject: [PATCH 028/207] Add contibutors to the release notes --- docs/release-notes/1.1.md | 18 ++++++++++++++++ docs/release-notes/2.0.md | 25 +++++++++++++++++++++++ docs/release-notes/2.1.md | 43 +++++++++++++++++++++++++++++++++++++++ docs/release-notes/2.2.md | 27 ++++++++++++++++++++++++ docs/release-notes/3.0.md | 28 +++++++++++++++++++++++++ 5 files changed, 141 insertions(+) diff --git a/docs/release-notes/1.1.md b/docs/release-notes/1.1.md index 11a7d3752d..371eeb26b8 100644 --- a/docs/release-notes/1.1.md +++ b/docs/release-notes/1.1.md @@ -28,3 +28,21 @@ First, Npgsql 1.0.x used a problematic method to identify serial (autoincrement) Unfortunately, this change will cause some incorrect changes the first time you add a migration after the upgrade. To avoid this, simply add a dummy migration right after upgrading to 1.1 and then delete the two new files generated for the dummy migration, *but keep the changes made to your ModelSnapshot.cs*. From this point on everything should be fine. *Make sure you have no pending changes to your model before doing this!*. Apologies for this problematic upgrade procedure, it should at least keep things clean going forward. + +## Contributors: + +Thank you very much to the following people who have contributed to the individual 1.1.x. releases. + +### [Milestone 1.1.1](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A1.1.1): + +| Contributor | Assigned issues | +| ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| +| [@roji](https://github.com/roji) | [8](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A1.1.1+is%3Aclosed+assignee%3Aroji) | + + +### [Milestone 1.1.0](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A1.1.0): + +| Contributor | Assigned issues | +| ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| +| [@roji](https://github.com/roji) | [11](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A1.1.0+is%3Aclosed+assignee%3Aroji) | + diff --git a/docs/release-notes/2.0.md b/docs/release-notes/2.0.md index 3ef18f78a3..6b95b57b31 100644 --- a/docs/release-notes/2.0.md +++ b/docs/release-notes/2.0.md @@ -17,3 +17,28 @@ Here's the [full list of issues](https://github.com/npgsql/Npgsql.EntityFramewor * Previously an Npgsql.EntityFrameworkCore.PostgreSQL.Design nuget package existed alongside the main package. Its contents have been merged into the main Npgsql.EntityFrameworkCore.PostgreSQL and no new version has been released. * Specifying versions when specifying PostgreSQL extensions on your model is no longer supported - this was a very rarely-used feature which interfered with extension scaffolding. + +## Contributors: + +Thank you very much to the following people who have contributed to the individual 2.0.x. releases. + +### [Milestone 2.0.2](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A2.0.2): + +| Contributor | Assigned issues | +| ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| +| [@roji](https://github.com/roji) | [4](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A2.0.2+is%3Aclosed+assignee%3Aroji) | + + +### [Milestone 2.0.1](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A2.0.1): + +| Contributor | Assigned issues | +| ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| +| [@roji](https://github.com/roji) | [5](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A2.0.1+is%3Aclosed+assignee%3Aroji) | + + +### [Milestone 2.0.0](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A2.0.0): + +| Contributor | Assigned issues | +| ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| +| [@roji](https://github.com/roji) | [16](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A2.0.0+is%3Aclosed+assignee%3Aroji) | + diff --git a/docs/release-notes/2.1.md b/docs/release-notes/2.1.md index 4ef3301ef3..290ad87f9c 100644 --- a/docs/release-notes/2.1.md +++ b/docs/release-notes/2.1.md @@ -79,3 +79,46 @@ Here's the [full list of issues](https://github.com/npgsql/Npgsql.EntityFramewor * If you're specifying index methods with `ForNpgsqlHasMethod()`, then you will have to fix migrations which generate those indexes. In these migrations, you will find code such as `.Annotation("Npgsql:Npgsql:IndexMethod", "gin")`. You must remove the extra `Npgsql:`, leaving `.Annotation("Npgsql:IndexMethod", "gin")`. * Specifying versions when specifying PostgreSQL extensions on your model is no longer supported - this was a very rarely-used feature which interfered with extension scaffolding. * If you're still referencing the nuget package Npgsql.EntityFrameworkCore.PostgreSQL.Design, please remove it - it's no longer needed or up to date. + +## Contributors: + +Thank you very much to the following people who have contributed to the individual 2.1.x. releases. + +### [Milestone 2.1.2](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A2.1.2): + +| Contributor | Assigned issues | +| ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| +| [@roji](https://github.com/roji) | [6](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A2.1.2+is%3Aclosed+assignee%3Aroji) | +| [@austindrenski](https://github.com/austindrenski) | [3](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A2.1.2+is%3Aclosed+assignee%3Aaustindrenski) | +| [@rwasef1830](https://github.com/rwasef1830) | [1](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A2.1.2+is%3Aclosed+assignee%3Arwasef1830) | + + +### [Milestone 2.1.11](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A2.1.11): + +| Contributor | Assigned issues | +| ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| +| [@roji](https://github.com/roji) | [1](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A2.1.11+is%3Aclosed+assignee%3Aroji) | + + +### [Milestone 2.1.1.1](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A2.1.1.1): + +| Contributor | Assigned issues | +| ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| +| [@roji](https://github.com/roji) | [4](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A2.1.1.1+is%3Aclosed+assignee%3Aroji) | + + +### [Milestone 2.1.1](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A2.1.1): + +| Contributor | Assigned issues | +| ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| +| [@roji](https://github.com/roji) | [9](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A2.1.1+is%3Aclosed+assignee%3Aroji) | + + +### [Milestone 2.1.0](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A2.1.0): + +| Contributor | Assigned issues | +| ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| +| [@roji](https://github.com/roji) | [24](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A2.1.0+is%3Aclosed+assignee%3Aroji) | +| [@austindrenski](https://github.com/austindrenski) | [1](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A2.1.0+is%3Aclosed+assignee%3Aaustindrenski) | +| [@rwasef1830](https://github.com/rwasef1830) | [1](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A2.1.0+is%3Aclosed+assignee%3Arwasef1830) | + diff --git a/docs/release-notes/2.2.md b/docs/release-notes/2.2.md index fb8e8bae47..f23dd55177 100644 --- a/docs/release-notes/2.2.md +++ b/docs/release-notes/2.2.md @@ -55,3 +55,30 @@ Thanks to [@khellang](https://github.com/khellang) for contributing this! * Many new SQL translations were added, so more of your LINQ expressions can run in the database. We'll be working on our documentation to make these more discoverable. The full list of issues for this release is [available here](https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL/issues?q=milestone%3A2.2.0+is%3Aclosed&utf8=%E2%9C%93). + +## Contributors: + +Thank you very much to the following people who have contributed to the individual 2.2.x. releases. + +### [Milestone 2.2.6](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A2.2.6): + +| Contributor | Assigned issues | +| ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| +| [@roji](https://github.com/roji) | [5](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A2.2.6+is%3Aclosed+assignee%3Aroji) | + + +### [Milestone 2.2.4](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A2.2.4): + +| Contributor | Assigned issues | +| ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| +| [@roji](https://github.com/roji) | [3](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A2.2.4+is%3Aclosed+assignee%3Aroji) | +| [@austindrenski](https://github.com/austindrenski) | [1](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A2.2.4+is%3Aclosed+assignee%3Aaustindrenski) | + + +### [Milestone 2.2.0](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A2.2.0): + +| Contributor | Assigned issues | +| ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| +| [@austindrenski](https://github.com/austindrenski) | [15](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A2.2.0+is%3Aclosed+assignee%3Aaustindrenski) | +| [@roji](https://github.com/roji) | [8](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A2.2.0+is%3Aclosed+assignee%3Aroji) | + diff --git a/docs/release-notes/3.0.md b/docs/release-notes/3.0.md index aa8cc4de8d..a80b9d7794 100644 --- a/docs/release-notes/3.0.md +++ b/docs/release-notes/3.0.md @@ -47,3 +47,31 @@ protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) ``` More information is available in [the page about generated properties](../modeling/generated-properties.md). + +## Contributors: + +Thank you very much to the following people who have contributed to the individual 3.0.x. releases. + +### [Milestone 3.0.2](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A3.0.2): + +| Contributor | Assigned issues | +| ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| +| [@roji](https://github.com/roji) | [2](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A3.0.2+is%3Aclosed+assignee%3Aroji) | +| [@MarioPrabowo](https://github.com/MarioPrabowo) | [1](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A3.0.2+is%3Aclosed+assignee%3AMarioPrabowo) | + + +### [Milestone 3.0.1](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A3.0.1): + +| Contributor | Assigned issues | +| ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| +| [@roji](https://github.com/roji) | [1](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A3.0.1+is%3Aclosed+assignee%3Aroji) | + + +### [Milestone 3.0.0](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A3.0.0): + +| Contributor | Assigned issues | +| ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| +| [@roji](https://github.com/roji) | [25](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A3.0.0+is%3Aclosed+assignee%3Aroji) | +| [@austindrenski](https://github.com/austindrenski) | [2](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A3.0.0+is%3Aclosed+assignee%3Aaustindrenski) | +| [@YohDeadfall](https://github.com/YohDeadfall) | [1](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A3.0.0+is%3Aclosed+assignee%3AYohDeadfall) | + From 7a2eb9eb1b9afe6a56edb3ed3099d20f93665fb3 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Mon, 28 Sep 2020 17:12:21 +0300 Subject: [PATCH 029/207] Fix badge link --- docs/index.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/index.md b/docs/index.md index b43fb027e2..00890c70eb 100644 --- a/docs/index.md +++ b/docs/index.md @@ -1,7 +1,7 @@ [![stable](https://img.shields.io/nuget/v/Npgsql.EntityFrameworkCore.PostgreSQL.svg?label=stable)](https://www.nuget.org/packages/Npgsql.EntityFrameworkCore.PostgreSQL/) [![unstable](https://img.shields.io/myget/npgsql-unstable/vpre/Npgsql.EntityFrameworkCore.PostgreSQL.svg?label=unstable)](https://www.myget.org/feed/npgsql-unstable/package/nuget/Npgsql.EntityFrameworkCore.PostgreSQL) [![next patch](https://img.shields.io/myget/npgsql/v/Npgsql.EntityFrameworkCore.PostgreSQL.svg?label=next%20patch)](https://www.myget.org/feed/npgsql/package/nuget/Npgsql.EntityFrameworkCore.PostgreSQL) -[![build](https://img.shields.io/github/workflow/status/efcore.pg/npgsql/Build)](https://github.com/npgsql/efcore.pg/actions) +[![build](https://img.shields.io/github/workflow/status/npgsql/efcore.pg/Build)](https://github.com/npgsql/efcore.pg/actions) [![gitter](https://img.shields.io/badge/gitter-join%20chat-brightgreen.svg)](https://gitter.im/npgsql/npgsql) # Getting Started From 032acfc841f3ec7532526e0926ee3a7af8547fff Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Mon, 28 Sep 2020 17:20:23 +0300 Subject: [PATCH 030/207] Rename 3.0 release notes to 3.x --- docs/release-notes/{3.0.md => 3.x.md} | 12 ++++++------ docs/toc.md | 2 +- 2 files changed, 7 insertions(+), 7 deletions(-) rename docs/release-notes/{3.0.md => 3.x.md} (90%) diff --git a/docs/release-notes/3.0.md b/docs/release-notes/3.x.md similarity index 90% rename from docs/release-notes/3.0.md rename to docs/release-notes/3.x.md index a80b9d7794..52697d2718 100644 --- a/docs/release-notes/3.0.md +++ b/docs/release-notes/3.x.md @@ -1,6 +1,6 @@ -# 3.0 Release Notes +# 3.x Release Notes -Version 3.0.0 of the Npgsql Entity Framework Core provider has been released and is available on nuget. This version works with [version 3.0.0 of Entity Framework Core](https://docs.microsoft.com/ef/core/what-is-new/ef-core-3.0), and bring new Npgsql features in addition to the general EF Core changes. +Version 3.1 of the Npgsql Entity Framework Core provider has been released and is available on nuget. This version works with [version 3.1 of Entity Framework Core](https://docs.microsoft.com/ef/core/what-is-new/ef-core-3.x), and brings new Npgsql features in addition to the general EF Core changes. > [!CAUTION] > Use these versions with care and do not deploy to production without thorough testing. Read the breaking changes section below. @@ -9,7 +9,7 @@ The full list of issues for this release is [available here](https://github.com/ ## New Features -Aside from general EF Core features new in 3.0.0, the Npgsql EF Core provider contains the following major new features: +Aside from general EF Core features new in 3.x, the Npgsql EF Core provider contains the following major new features: * It is now possible to map POCOs to JSON columns and query them, [see the docs for more info](../mapping/json.md) ([#981](https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL/issues/981)) * PostgreSQL identity columns are now the default - see breaking changes below) ([#804](https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL/issues/804)) @@ -26,11 +26,11 @@ Aside from general EF Core features new in 3.0.0, the Npgsql EF Core provider co ### Default value generation strategy is now IDENTITY > [!CAUTION] -> This is a major change, and upgrading to 3.0 with an existing database will cause a non-trivial schema migration to be generated. Read the following carefully. +> This is a major change, and upgrading to 3.x with an existing database will cause a non-trivial schema migration to be generated. Read the following carefully. The default value generation strategy has changed from the older SERIAL columns to the newer IDENTITY columns, introduced in PostgreSQL 10. -When producing a migration with 3.0, the Npgsql provider will attempt to automatically generate SQL to alter your tables and convert serial columns to identity ones. This is a sensitive, one-time migration operation that should be done with care, and carefully tested before deployment to production. +When producing a migration with 3.x, the Npgsql provider will attempt to automatically generate SQL to alter your tables and convert serial columns to identity ones. This is a sensitive, one-time migration operation that should be done with care, and carefully tested before deployment to production. If you wish to opt out of using IDENTITY columns and continue using SERIAL columns, set the following on your model: @@ -50,7 +50,7 @@ More information is available in [the page about generated properties](../modeli ## Contributors: -Thank you very much to the following people who have contributed to the individual 3.0.x. releases. +Thank you very much to the following people who have contributed to the individual 3.x releases. ### [Milestone 3.0.2](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A3.0.2): diff --git a/docs/toc.md b/docs/toc.md index 65d73b42bb..a4522e3aed 100644 --- a/docs/toc.md +++ b/docs/toc.md @@ -1,6 +1,6 @@ # [Getting Started](index.md) # Release Notes -## [3.0](release-notes/3.0.md) +## [3.x](release-notes/3.x.md) ## [2.2](release-notes/2.2.md) ## [2.1](release-notes/2.1.md) ## [2.0](release-notes/2.0.md) From 66f775c7f2d061bfbd7b1c01598a9ecae648c335 Mon Sep 17 00:00:00 2001 From: Brar Piening Date: Mon, 28 Sep 2020 22:02:04 +0200 Subject: [PATCH 031/207] Contribution info on EFCore.PG erroneously points to Npgsql Also merge contribution info from 3.0 and 3.1 into 3.x Closes #54 --- docs/release-notes/1.1.md | 9 +++-- docs/release-notes/2.0.md | 13 ++++---- docs/release-notes/2.1.md | 29 ++++++++-------- docs/release-notes/2.2.md | 17 +++++----- docs/release-notes/3.x.md | 69 ++++++++++++++++++++++++++++++++++----- 5 files changed, 92 insertions(+), 45 deletions(-) diff --git a/docs/release-notes/1.1.md b/docs/release-notes/1.1.md index 371eeb26b8..55efa5e15e 100644 --- a/docs/release-notes/1.1.md +++ b/docs/release-notes/1.1.md @@ -33,16 +33,15 @@ Apologies for this problematic upgrade procedure, it should at least keep things Thank you very much to the following people who have contributed to the individual 1.1.x. releases. -### [Milestone 1.1.1](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A1.1.1): +### [Milestone 1.1.1](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A1.1.1): | Contributor | Assigned issues | | ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| -| [@roji](https://github.com/roji) | [8](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A1.1.1+is%3Aclosed+assignee%3Aroji) | +| [@roji](https://github.com/roji) | [8](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A1.1.1+is%3Aclosed+assignee%3Aroji) | -### [Milestone 1.1.0](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A1.1.0): +### [Milestone 1.1.0](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A1.1.0): | Contributor | Assigned issues | | ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| -| [@roji](https://github.com/roji) | [11](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A1.1.0+is%3Aclosed+assignee%3Aroji) | - +| [@roji](https://github.com/roji) | [11](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A1.1.0+is%3Aclosed+assignee%3Aroji) | diff --git a/docs/release-notes/2.0.md b/docs/release-notes/2.0.md index 6b95b57b31..32d433a8df 100644 --- a/docs/release-notes/2.0.md +++ b/docs/release-notes/2.0.md @@ -22,23 +22,22 @@ Here's the [full list of issues](https://github.com/npgsql/Npgsql.EntityFramewor Thank you very much to the following people who have contributed to the individual 2.0.x. releases. -### [Milestone 2.0.2](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A2.0.2): +### [Milestone 2.0.2](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.0.2): | Contributor | Assigned issues | | ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| -| [@roji](https://github.com/roji) | [4](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A2.0.2+is%3Aclosed+assignee%3Aroji) | +| [@roji](https://github.com/roji) | [4](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.0.2+is%3Aclosed+assignee%3Aroji) | -### [Milestone 2.0.1](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A2.0.1): +### [Milestone 2.0.1](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.0.1): | Contributor | Assigned issues | | ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| -| [@roji](https://github.com/roji) | [5](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A2.0.1+is%3Aclosed+assignee%3Aroji) | +| [@roji](https://github.com/roji) | [5](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.0.1+is%3Aclosed+assignee%3Aroji) | -### [Milestone 2.0.0](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A2.0.0): +### [Milestone 2.0.0](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.0.0): | Contributor | Assigned issues | | ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| -| [@roji](https://github.com/roji) | [16](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A2.0.0+is%3Aclosed+assignee%3Aroji) | - +| [@roji](https://github.com/roji) | [16](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.0.0+is%3Aclosed+assignee%3Aroji) | diff --git a/docs/release-notes/2.1.md b/docs/release-notes/2.1.md index 290ad87f9c..71f10a786d 100644 --- a/docs/release-notes/2.1.md +++ b/docs/release-notes/2.1.md @@ -84,41 +84,40 @@ Here's the [full list of issues](https://github.com/npgsql/Npgsql.EntityFramewor Thank you very much to the following people who have contributed to the individual 2.1.x. releases. -### [Milestone 2.1.2](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A2.1.2): +### [Milestone 2.1.2](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.1.2): | Contributor | Assigned issues | | ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| -| [@roji](https://github.com/roji) | [6](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A2.1.2+is%3Aclosed+assignee%3Aroji) | -| [@austindrenski](https://github.com/austindrenski) | [3](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A2.1.2+is%3Aclosed+assignee%3Aaustindrenski) | -| [@rwasef1830](https://github.com/rwasef1830) | [1](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A2.1.2+is%3Aclosed+assignee%3Arwasef1830) | +| [@roji](https://github.com/roji) | [6](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.1.2+is%3Aclosed+assignee%3Aroji) | +| [@austindrenski](https://github.com/austindrenski) | [3](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.1.2+is%3Aclosed+assignee%3Aaustindrenski) | +| [@rwasef1830](https://github.com/rwasef1830) | [1](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.1.2+is%3Aclosed+assignee%3Arwasef1830) | -### [Milestone 2.1.11](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A2.1.11): +### [Milestone 2.1.11](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.1.11): | Contributor | Assigned issues | | ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| -| [@roji](https://github.com/roji) | [1](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A2.1.11+is%3Aclosed+assignee%3Aroji) | +| [@roji](https://github.com/roji) | [1](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.1.11+is%3Aclosed+assignee%3Aroji) | -### [Milestone 2.1.1.1](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A2.1.1.1): +### [Milestone 2.1.1.1](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.1.1.1): | Contributor | Assigned issues | | ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| -| [@roji](https://github.com/roji) | [4](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A2.1.1.1+is%3Aclosed+assignee%3Aroji) | +| [@roji](https://github.com/roji) | [4](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.1.1.1+is%3Aclosed+assignee%3Aroji) | -### [Milestone 2.1.1](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A2.1.1): +### [Milestone 2.1.1](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.1.1): | Contributor | Assigned issues | | ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| -| [@roji](https://github.com/roji) | [9](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A2.1.1+is%3Aclosed+assignee%3Aroji) | +| [@roji](https://github.com/roji) | [9](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.1.1+is%3Aclosed+assignee%3Aroji) | -### [Milestone 2.1.0](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A2.1.0): +### [Milestone 2.1.0](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.1.0): | Contributor | Assigned issues | | ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| -| [@roji](https://github.com/roji) | [24](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A2.1.0+is%3Aclosed+assignee%3Aroji) | -| [@austindrenski](https://github.com/austindrenski) | [1](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A2.1.0+is%3Aclosed+assignee%3Aaustindrenski) | -| [@rwasef1830](https://github.com/rwasef1830) | [1](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A2.1.0+is%3Aclosed+assignee%3Arwasef1830) | - +| [@roji](https://github.com/roji) | [24](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.1.0+is%3Aclosed+assignee%3Aroji) | +| [@austindrenski](https://github.com/austindrenski) | [1](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.1.0+is%3Aclosed+assignee%3Aaustindrenski) | +| [@rwasef1830](https://github.com/rwasef1830) | [1](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.1.0+is%3Aclosed+assignee%3Arwasef1830) | diff --git a/docs/release-notes/2.2.md b/docs/release-notes/2.2.md index f23dd55177..71378f5620 100644 --- a/docs/release-notes/2.2.md +++ b/docs/release-notes/2.2.md @@ -60,25 +60,24 @@ The full list of issues for this release is [available here](https://github.com/ Thank you very much to the following people who have contributed to the individual 2.2.x. releases. -### [Milestone 2.2.6](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A2.2.6): +### [Milestone 2.2.6](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.2.6): | Contributor | Assigned issues | | ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| -| [@roji](https://github.com/roji) | [5](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A2.2.6+is%3Aclosed+assignee%3Aroji) | +| [@roji](https://github.com/roji) | [5](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.2.6+is%3Aclosed+assignee%3Aroji) | -### [Milestone 2.2.4](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A2.2.4): +### [Milestone 2.2.4](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.2.4): | Contributor | Assigned issues | | ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| -| [@roji](https://github.com/roji) | [3](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A2.2.4+is%3Aclosed+assignee%3Aroji) | -| [@austindrenski](https://github.com/austindrenski) | [1](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A2.2.4+is%3Aclosed+assignee%3Aaustindrenski) | +| [@roji](https://github.com/roji) | [3](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.2.4+is%3Aclosed+assignee%3Aroji) | +| [@austindrenski](https://github.com/austindrenski) | [1](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.2.4+is%3Aclosed+assignee%3Aaustindrenski) | -### [Milestone 2.2.0](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A2.2.0): +### [Milestone 2.2.0](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.2.0): | Contributor | Assigned issues | | ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| -| [@austindrenski](https://github.com/austindrenski) | [15](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A2.2.0+is%3Aclosed+assignee%3Aaustindrenski) | -| [@roji](https://github.com/roji) | [8](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A2.2.0+is%3Aclosed+assignee%3Aroji) | - +| [@austindrenski](https://github.com/austindrenski) | [15](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.2.0+is%3Aclosed+assignee%3Aaustindrenski) | +| [@roji](https://github.com/roji) | [8](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.2.0+is%3Aclosed+assignee%3Aroji) | diff --git a/docs/release-notes/3.x.md b/docs/release-notes/3.x.md index 52697d2718..b466fee4bd 100644 --- a/docs/release-notes/3.x.md +++ b/docs/release-notes/3.x.md @@ -52,26 +52,77 @@ More information is available in [the page about generated properties](../modeli Thank you very much to the following people who have contributed to the individual 3.x releases. -### [Milestone 3.0.2](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A3.0.2): +### [Milestone 3.1.7](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.1.7): | Contributor | Assigned issues | | ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| -| [@roji](https://github.com/roji) | [2](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A3.0.2+is%3Aclosed+assignee%3Aroji) | -| [@MarioPrabowo](https://github.com/MarioPrabowo) | [1](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A3.0.2+is%3Aclosed+assignee%3AMarioPrabowo) | +| [@roji](https://github.com/roji) | [4](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.1.7+is%3Aclosed+assignee%3Aroji) | -### [Milestone 3.0.1](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A3.0.1): +### [Milestone 3.1.4](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.1.4): | Contributor | Assigned issues | | ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| -| [@roji](https://github.com/roji) | [1](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A3.0.1+is%3Aclosed+assignee%3Aroji) | +| [@roji](https://github.com/roji) | [4](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.1.4+is%3Aclosed+assignee%3Aroji) | -### [Milestone 3.0.0](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A3.0.0): +### [Milestone 3.1.3](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.1.3): | Contributor | Assigned issues | | ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| -| [@roji](https://github.com/roji) | [25](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A3.0.0+is%3Aclosed+assignee%3Aroji) | -| [@austindrenski](https://github.com/austindrenski) | [2](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A3.0.0+is%3Aclosed+assignee%3Aaustindrenski) | -| [@YohDeadfall](https://github.com/YohDeadfall) | [1](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A3.0.0+is%3Aclosed+assignee%3AYohDeadfall) | +| [@roji](https://github.com/roji) | [1](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.1.3+is%3Aclosed+assignee%3Aroji) | + +### [Milestone 3.1.2](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.1.2): + +| Contributor | Assigned issues | +| ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| +| [@roji](https://github.com/roji) | [3](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.1.2+is%3Aclosed+assignee%3Aroji) | +| [@grzybsonssg](https://github.com/grzybsonssg) | [1](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.1.2+is%3Aclosed+assignee%3Agrzybsonssg) | + + +### [Milestone 3.1.1.2](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.1.1.2): + +| Contributor | Assigned issues | +| ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| +| [@roji](https://github.com/roji) | [1](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.1.1.2+is%3Aclosed+assignee%3Aroji) | + + +### [Milestone 3.1.1.1](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.1.1.1): + +| Contributor | Assigned issues | +| ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| +| [@roji](https://github.com/roji) | [1](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.1.1.1+is%3Aclosed+assignee%3Aroji) | + + +### [Milestone 3.1.1](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.1.1): + +| Contributor | Assigned issues | +| ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| +| [@roji](https://github.com/roji) | [6](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.1.1+is%3Aclosed+assignee%3Aroji) | + + +### [Milestone 3.1.0](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.1.0): + +| Contributor | Assigned issues | +| ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| +| [@roji](https://github.com/roji) | [15](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.1.0+is%3Aclosed+assignee%3Aroji) | +| [@austindrenski](https://github.com/austindrenski) | [1](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.1.0+is%3Aclosed+assignee%3Aaustindrenski) | +| [@ins0mniaque](https://github.com/ins0mniaque) | [1](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.1.0+is%3Aclosed+assignee%3Ains0mniaque) | +| [@MarioPrabowo](https://github.com/MarioPrabowo) | [1](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.1.0+is%3Aclosed+assignee%3AMarioPrabowo) | + + +### [Milestone 3.0.1](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.0.1): + +| Contributor | Assigned issues | +| ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| +| [@roji](https://github.com/roji) | [1](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.0.1+is%3Aclosed+assignee%3Aroji) | + + +### [Milestone 3.0.0](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.0.0): + +| Contributor | Assigned issues | +| ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| +| [@roji](https://github.com/roji) | [25](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.0.0+is%3Aclosed+assignee%3Aroji) | +| [@austindrenski](https://github.com/austindrenski) | [2](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.0.0+is%3Aclosed+assignee%3Aaustindrenski) | +| [@YohDeadfall](https://github.com/YohDeadfall) | [1](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.0.0+is%3Aclosed+assignee%3AYohDeadfall) | From 898ab36df2bded8b8b99090c8874d3e11bad9e2a Mon Sep 17 00:00:00 2001 From: sid-g Date: Thu, 8 Oct 2020 00:51:45 -0500 Subject: [PATCH 032/207] Minor grammar correction to caution message (#55) --- docs/modeling/generated-properties.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/modeling/generated-properties.md b/docs/modeling/generated-properties.md index 900f1c0f7d..66011b382c 100644 --- a/docs/modeling/generated-properties.md +++ b/docs/modeling/generated-properties.md @@ -1,7 +1,7 @@ # Value Generation > [!CAUTION] -> In 3.0.0, the default value generation strategy has changed from the older SERIAL columns to the newer IDENTITY columns. Read the below carefully if you are migrating an existing database. +> In 3.0.0, the default value generation strategy has changed from the older SERIAL columns to the newer IDENTITY columns. Read the information below carefully if you are migrating an existing database. > [!NOTE] > It's recommended that you start by reading the general [Entity Framework Core docs on generated properties](https://docs.microsoft.com/en-us/ef/core/modeling/generated-properties). From c006b424316b907f28f26be34746d1aff82681e0 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Fri, 9 Oct 2020 11:07:21 +0300 Subject: [PATCH 033/207] Various minor fixes to EFCore.PG docs Linting etc. --- docs/index.md | 1 + docs/mapping/array.md | 4 ++-- docs/mapping/enum.md | 4 ++-- docs/mapping/full-text-search.md | 9 ++++---- docs/mapping/general.md | 2 +- docs/mapping/json.md | 13 ++++++----- docs/mapping/nodatime.md | 4 ++-- docs/mapping/nts.md | 2 +- docs/mapping/range.md | 20 ++++++++--------- docs/modeling/concurrency.md | 6 +++--- docs/modeling/generated-properties.md | 2 +- docs/modeling/indexes.md | 1 + docs/release-notes/2.0.md | 10 ++++----- docs/release-notes/2.1.md | 14 +++++------- docs/release-notes/2.2.md | 10 ++++----- docs/release-notes/3.x.md | 31 ++++++++++----------------- 16 files changed, 58 insertions(+), 75 deletions(-) diff --git a/docs/index.md b/docs/index.md index 00890c70eb..c3ae340557 100644 --- a/docs/index.md +++ b/docs/index.md @@ -77,6 +77,7 @@ public void ConfigureServices(IServiceCollection services) options.UseNpgsql(Configuration.GetConnectionString("BloggingContext"))); } ``` + ## 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: diff --git a/docs/mapping/array.md b/docs/mapping/array.md index 505129c3b3..2a93e46ab0 100644 --- a/docs/mapping/array.md +++ b/docs/mapping/array.md @@ -5,7 +5,7 @@ PostgreSQL has the unique feature of supporting [*array data types*](https://www > [!NOTE] > Although PostgreSQL supports multidimensional arrays, these aren't yet supported by the EF Core provider. -# Mapping arrays +## Mapping arrays Simply define a regular .NET array or `List<>` property, and the provider @@ -21,7 +21,7 @@ public class Post The provider will create `text[]` columns for the above two properties, and will properly detect changes in them - if you load an array and change one of its elements, calling `SaveChanges()` will automatically update the row in the database accordingly. -# Operation translation +## Operation translation The provider can also translate CLR array operations to the corresponding SQL operation; this allows you to efficiently work with arrays by evaluating operations in the database and avoids pulling all the data. The following table lists the range operations that currently get translated. If you run into a missing operation, please open an issue. diff --git a/docs/mapping/enum.md b/docs/mapping/enum.md index 5fbc0b0822..13cee4e3c1 100644 --- a/docs/mapping/enum.md +++ b/docs/mapping/enum.md @@ -8,14 +8,14 @@ However, the Npgsql provider also allows you to map your CLR enums to [database First, you must specify the PostgreSQL enum type on your model, just like you would with tables, sequences or other databases objects: -# [Version 2.2+](#tab/tabid-1) +### [Version 2.2+](#tab/tabid-1) ```c# protected override void OnModelCreating(ModelBuilder builder) => builder.HasPostgresEnum(); ``` -# [Version 2.1](#tab/tabid-2) +### [Version 2.1](#tab/tabid-2) ```c# protected override void OnModelCreating(ModelBuilder builder) diff --git a/docs/mapping/full-text-search.md b/docs/mapping/full-text-search.md index dd92fe0b3b..329c3d6329 100644 --- a/docs/mapping/full-text-search.md +++ b/docs/mapping/full-text-search.md @@ -32,7 +32,6 @@ Almost all PostgreSQL full text search functions can be called through LINQ quer | .Select(c => EF.Functions.ToTsVector(c.Name).SetWeight(NpgsqlTsVector.Lexeme.Weight.A)) | [SELECT setweight(to_tsvector(c."Name"), 'A')](https://www.postgresql.org/docs/current/static/textsearch-features.html#TEXTSEARCH-MANIPULATE-TSVECTOR) | .Where(c => c.SearchVector.Matches(EF.Functions.ToTsQuery("Npgsql")))
.OrderByDescending(c => c.SearchVector.Rank(EF.Functions.ToTsQuery("Npgsql"))) | WHERE (c."SearchVector" @@ to_tsquery('Npgsql'))
ORDER BY ts_rank(c."SearchVector", to_tsquery('Npgsql')) DESC - ## Setting up and querying a full text search index on an entity [As the PostgreSQL documentation explains](https://www.postgresql.org/docs/current/static/textsearch-tables.html), full-text search requires an index to run efficiently. This section will show two ways to do this, each having its benefits and drawbacks. Please read the PostgreSQL docs for more information on the two different approaches. @@ -53,7 +52,7 @@ public class Product Setting up the column to be auto-updated depends on your PostgreSQL version. On PostgreSQL 12 and above, the column can be a simple [generated column](../modeling/generated-properties##computed-columns-on-add-or-update), and version 5.0.0 contains sugar for setting that up. In previous versions, you must manually set up database triggers that update the column instead. -# [PostgreSQL 12+](#tab/pg12) +#### [PostgreSQL 12+](#tab/pg12) > [!NOTE] > The below only works on PostgreSQL 12 and version 5.0.0 of the EF Core provider. @@ -72,7 +71,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) .HasMethod("GIN"); // Index method on the search vector (GIN or GIST) ``` -# [Older Versions](#tab/pgold) +#### [Older Versions](#tab/pgold) First, modify the `OnModelCreating()` of your context class to add an index as follows: @@ -126,7 +125,7 @@ var npgsql = context.Products Version 5.0.0 of the provider includes sugar for defining the appropriate expression index; if you're using an older version, you'll have to define a raw SQL migration yourself. -# [EF Core 5+](#tab/pg12) +#### [EF Core 5+](#tab/pg12) ```c# modelBuilder.Entity() @@ -134,7 +133,7 @@ modelBuilder.Entity() .IsTsVectorExpressionIndex("english"); ``` -# [Older Versions](#tab/efold) +#### [Older Versions](#tab/efold) Create a migration which will contain the index creation SQL (`dotnet ef migrations add ...`). At this point, open the generated migration with your editor and add the following: diff --git a/docs/mapping/general.md b/docs/mapping/general.md index a9415d4d4b..f3138f154b 100644 --- a/docs/mapping/general.md +++ b/docs/mapping/general.md @@ -19,7 +19,7 @@ Special types such as [arrays](array.md) and [enums](enum.md) have their own doc [PostgreSQL composite types](https://www.postgresql.org/docs/current/static/rowtypes.html), while supported at the ADO.NET level, aren't yet supported in the EF Core provider. This is tracked by [#22](https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL/issues/22). -# Explicitly specifying data types +## Explicitly specifying data types In some cases, your .NET property type can be mapped to several PostgreSQL data types; a good example is a `string`, which will be mapped to `text` by default, but can also be mapped to `jsonb`. You can use either Data Annotation attributes or the Fluent API to configure the PostgreSQL data type: diff --git a/docs/mapping/json.md b/docs/mapping/json.md index ee187cd8e9..b2937578a2 100644 --- a/docs/mapping/json.md +++ b/docs/mapping/json.md @@ -58,7 +58,7 @@ If your column's JSON documents have a stable schema, you can map them to your o Mapping POCOs is extremely easy: simply add a property with your custom POCO type and instruct the provider to map it to JSON: -# [Data Annotations](#tab/data-annotations) +### [Data Annotations](#tab/data-annotations) ```c# public class SomeEntity @@ -82,7 +82,7 @@ public class Order // Part of the JSON column } ``` -# [Fluent API](#tab/fluent-api) +### [Fluent API](#tab/fluent-api) ```c# class MyContext : DbContext @@ -166,7 +166,7 @@ Console.WriteLine(someEntity.Customer.GetProperty("Orders")[0].GetProperty("Pric Saving and loading documents these documents wouldn't be much use without the ability to query them. You can express your queries via the same LINQ constructs you are already using in EF Core: -# [POCO Mapping](#tab/poco) +### [POCO Mapping](#tab/poco) ```c# var joes = context.CustomerEntries @@ -174,7 +174,7 @@ var joes = context.CustomerEntries .ToList(); ``` -# [JsonDocument Mapping](#tab/jsondocument) +### [JsonDocument Mapping](#tab/jsondocument) ```c# var joes = context.CustomerEntries @@ -196,7 +196,7 @@ WHERE c.""Customer""->>'Name' = 'Joe' The following expression types and functions are translated: -# [POCO Mapping](#tab/poco) +### [POCO Mapping](#tab/poco) | C# expression | SQL generated by Npgsql | |-------------------------------------------------------------------------------------------|------------------------------| @@ -210,7 +210,7 @@ The following expression types and functions are translated: | `.Where(e => EF.Functions.JsonExistsAll(e.Customer, "Age", "Address")` | [`WHERE "Customer" ?& ARRAY['Age','Address']`](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) | `.Where(e => EF.Functions.JsonTypeof(e.Customer.Age) == "number")` | [`WHERE jsonb_typeof("Customer"->'Age') = 'number'`](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-PROCESSING-TABLE) -# [JsonDocument Mapping](#tab/jsondocument) +### [JsonDocument Mapping](#tab/jsondocument) | C# expression | SQL generated by Npgsql | |-------------------------------------------------------------------------------------------|------------------------------| @@ -232,4 +232,3 @@ The following expression types and functions are translated: > A section on indices will be added. In the meantime consult the PostgreSQL documentation and other guides on the Internet. These are early days for EF Core JSON support, and you'll likely run into some limitations. Please let us know how the current features are working for you and what you'd like to see. - diff --git a/docs/mapping/nodatime.md b/docs/mapping/nodatime.md index 3c2c1fb520..2f72b730c4 100644 --- a/docs/mapping/nodatime.md +++ b/docs/mapping/nodatime.md @@ -1,6 +1,6 @@ # Date/Time Mapping with NodaTime -# What is NodaTime? +## What is NodaTime? By default, [the PostgreSQL date/time types](https://www.postgresql.org/docs/current/static/datatype-datetime.html) are mapped to the built-in .NET types (`DateTime`, `TimeSpan`). Unfortunately, these built-in types are flawed in many ways. The [NodaTime library](http://nodatime.org/) was created to solve many of these problems, and if your application handles dates and times in anything but the most basic way, you should consider using it. To learn more [read this blog post by Jon Skeet](http://blog.nodatime.org/2011/08/what-wrong-with-datetime-anyway.html). @@ -10,7 +10,7 @@ Beyond NodaTime's general advantages, some specific advantages NodaTime for Post * `Period` is much more suitable for mapping PostgreSQL `interval` than `TimeSpan`. * NodaTime types can fully represent PostgreSQL's microsecond precision, and can represent dates outside the BCL's date limit (1AD-9999AD). -# Setup +## Setup To set up the NodaTime plugin, add the [Npgsql.EntityFrameworkCore.PostgreSQL.NodaTime nuget](https://www.nuget.org/packages/Npgsql.EntityFrameworkCore.PostgreSQL.NodaTime) to your project. Then, make the following modification to your `UseNpgsql()` line: diff --git a/docs/mapping/nts.md b/docs/mapping/nts.md index 04ca5d952d..abdbb17368 100644 --- a/docs/mapping/nts.md +++ b/docs/mapping/nts.md @@ -62,7 +62,7 @@ Note that the plugin is far from covering all spatial operations. If an operatio |----------------------------------------------------------|---------------------------------| | .Where(c => c.Polygon.Area() > x) | [WHERE ST_Area(c."Polygon") > x](https://postgis.net/docs/manual-2.4/ST_Area.html) | .Where(c => c.Polygon.AsText() = x | [WHERE ST_AsText(c."Polygon") = x](https://postgis.net/docs/manual-2.4/ST_AsText.html) -| .Where(c => c.Polygon.Boundary = x | [WHERE ST_AsCoundary(c."Polygon") = x](https://postgis.net/docs/manual-2.4/ST_Boundary.html) +| .Where(c => c.Polygon.Boundary = x | [WHERE ST_Boundary(c."Polygon") = x](https://postgis.net/docs/manual-2.4/ST_Boundary.html) | .Where(c => c.Polygon.Contains(x)) | [WHERE ST_Contains(c."Polygon", x)](https://postgis.net/docs/manual-2.4/ST_Contains.html) | .Where(c => c.Polygon.Covers(x)) | [WHERE ST_Covers(c."Polygon", x)](https://postgis.net/docs/manual-2.4/ST_Covers.html) | .Where(c => c.Polygon.CoveredBy(x)) | [WHERE ST_CoveredBy(c."Polygon", x)](https://postgis.net/docs/manual-2.4/ST_CoveredBy.html) diff --git a/docs/mapping/range.md b/docs/mapping/range.md index db43b32994..e9f05e3d4e 100644 --- a/docs/mapping/range.md +++ b/docs/mapping/range.md @@ -1,10 +1,10 @@ # Range Type Mapping -PostgreSQL has the unique feature of supporting [*range data types*](https://www.postgresql.org/docs/current/static/rangetypes.html). Ranges represent a range of numbers, dates or other data types, and allow you to easily query ranges which contain a value, perform set operations (e.g. query ranges which contain other ranges), and other similar operations. The range operations supported by PostgreSQL are listed [in this page](https://www.postgresql.org/docs/current/static/functions-range.html). The Npgsql EF Core provider allows you to seemlessly map PostgreSQL ranges, and even perform operations on them that get translated to SQL for server evaluation. +PostgreSQL has the unique feature of supporting [*range data types*](https://www.postgresql.org/docs/current/static/rangetypes.html). Ranges represent a range of numbers, dates or other data types, and allow you to easily query ranges which contain a value, perform set operations (e.g. query ranges which contain other ranges), and other similar operations. The range operations supported by PostgreSQL are listed [in this page](https://www.postgresql.org/docs/current/static/functions-range.html). The Npgsql EF Core provider allows you to seamlessly map PostgreSQL ranges, and even perform operations on them that get translated to SQL for server evaluation. -# Mapping ranges +## Mapping ranges -Npgsql maps PostgreSQL ranges to the generic CLR type `NpgqslRange`: +Npgsql maps PostgreSQL ranges to the generic CLR type `NpgsqlRange`: ```c# public class Event @@ -17,7 +17,7 @@ public class Event This will create a column of type `daterange` in your database. You can similarly have properties of type `NpgsqlRange`, `NpgsqlRange`, etc. -# User-defined ranges +## User-defined ranges > [!NOTE] > This feature was introduced in version 2.2 @@ -25,6 +25,7 @@ This will create a column of type `daterange` in your database. You can similarl PostgreSQL comes with 6 built-in ranges: `int4range`, `int8range`, `numrange`, `tsrange`, `tstzrange`, `daterange`; these can be used simply by adding the appropriate `NpgsqlRange` property in your entities as shown above. You can also define your own range types over arbitrary types, and use those in EF Core as well. To make the EF Core type mapper aware of your user-defined range, call the `MapRange()` method in your context's `OnConfiguring()` method as follows: + ```c# protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) => optionsBuilder.UseNpgsql( @@ -43,7 +44,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) This will cause the appropriate [`CREATE TYPE ... AS RANGE`](https://www.postgresql.org/docs/current/static/sql-createtype.html) statement to be generated in your migrations, ensuring that your range is created and ready for use. Note that `HasPostgresRange()` supports additional parameters as supported by PostgreSQL `CREATE TYPE`. -# Operation translation +## Operation translation Ranges can be queried via extensions methods on `NpgsqlRange`: @@ -51,7 +52,7 @@ Ranges can be queried via extensions methods on `NpgsqlRange`: var events = context.Events.Where(p => p.Duration.Contains(someDate)); ``` -This will translate to an SQL operation using the PostgreSQL `@>` operator, evaluating at the server and saving you from transfering the entire `Events` table to the client. Note that you can (and probably should) create indexes to make this operation more efficient, see the PostgreSQL docs for more info. +This will translate to an SQL operation using the PostgreSQL `@>` operator, evaluating at the server and saving you from transferring the entire `Events` table to the client. Note that you can (and probably should) create indexes to make this operation more efficient, see the PostgreSQL docs for more info. The following table lists the range operations that currently get translated. If you run into a missing operation, please open an issue. @@ -68,7 +69,6 @@ The following table lists the range operations that currently get translated. If | `.Where(c => c.SomeRange.DoesNotExtendLeftOf(otherRange))` | [`WHERE x."SomeRange" &> @__otherRange_0`](https://www.postgresql.org/docs/current/static/functions-range.html#RANGE-OPERATORS-TABLE) | `.Where(c => c.SomeRange.DoesNotExtendRightOf(otherRange))`| [`WHERE x."SomeRange" <& @__otherRange_0`](https://www.postgresql.org/docs/current/static/functions-range.html#RANGE-OPERATORS-TABLE) | `.Where(c => c.SomeRange.IsAdjacentTo(otherRange))` | [`WHERE x."SomeRange" -\|- @__otherRange_0`](https://www.postgresql.org/docs/current/static/functions-range.html#RANGE-OPERATORS-TABLE) -| `.Select(c => c.SomeRange.Union(otherRange))` | [`SELECT x."SomeRange" + @__otherRange_0`](https://www.postgresql.org/docs/current/static/functions-range.html#RANGE-OPERATORS-TABLE) -| `.Select(c => c.SomeRange.Intersect(otherRange))` | [`SELECT x."SomeRange" * @__otherRange_0`](https://www.postgresql.org/docs/current/static/functions-range.html#RANGE-OPERATORS-TABLE) -| `.Select(c => c.SomeRange.Except(otherRange))` | [`SELECT x."SomeRange" - @__otherRange_0`](https://www.postgresql.org/docs/current/static/functions-range.html#RANGE-OPERATORS-TABLE) - +| `.Select(c => c.SomeRange.Union(otherRange))` | [`SELECT x."SomeRange" + @__otherRange_0`](https://www.postgresql.org/docs/current/static/functions-range.html#RANGE-OPERATORS-TABLE) +| `.Select(c => c.SomeRange.Intersect(otherRange))` | [`SELECT x."SomeRange" * @__otherRange_0`](https://www.postgresql.org/docs/current/static/functions-range.html#RANGE-OPERATORS-TABLE) +| `.Select(c => c.SomeRange.Except(otherRange))` | [`SELECT x."SomeRange" - @__otherRange_0`](https://www.postgresql.org/docs/current/static/functions-range.html#RANGE-OPERATORS-TABLE) diff --git a/docs/modeling/concurrency.md b/docs/modeling/concurrency.md index f01a7b40b6..57b13cabfc 100644 --- a/docs/modeling/concurrency.md +++ b/docs/modeling/concurrency.md @@ -17,12 +17,12 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) .UseXminAsConcurrencyToken(); ``` -Note that by default, this will set up a [shadow property](https://docs.microsoft.com/en-us/ef/core/modeling/shadow-properties) called `xmin` on your entity. This means that when you load an entity from the database, the value of `xmin` will be stored in the context, making it impossible to use that instance with another context (without reloading the entity). If you plan to pass instances between different contexts, consider adding an `xmin` property of type `uint` on your entity; this will automatically cause the concurrency token to be stored on the instance instead: +Note that by default, this will set up a [shadow property](https://docs.microsoft.com/ef/core/modeling/shadow-properties) called `xmin` on your entity. This means that when you load an entity from the database, the value of `xmin` will be stored in the context, making it impossible to use that instance with another context (without reloading the entity). If you plan to pass instances between different contexts, consider adding an `xmin` property of type `uint` on your entity; this will automatically cause the concurrency token to be stored on the instance instead: ```c# class Blog { - ... - public uint xmin { get; set; } + ... + public uint xmin { get; set; } } ``` diff --git a/docs/modeling/generated-properties.md b/docs/modeling/generated-properties.md index 66011b382c..362d0dc64a 100644 --- a/docs/modeling/generated-properties.md +++ b/docs/modeling/generated-properties.md @@ -82,7 +82,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) ## HiLo Autoincrement Generation -One disadvantage of database-generated values is that these values must be read back from the database after a row is inserted. If you're saving multiple related entities, this means you must perform multiple roundtrips as the first entity's generated key must be read before writing the second one. One solution to this problem is HiLo value generation: rather than relying on the database to generate each and every value, the application "allocates" a range of values, which it can then populate directly on new entities without any additional roundtrips. When the range is exhausted, a new range is allocated. In practical terms, this uses a sequence that increments by some large value (100 by default), allowing the application to insert 100 rows autonomously. +One disadvantage of database-generated values is that these values must be read back from the database after a row is inserted. If you're saving multiple related entities, this means you must perform multiple round-trips as the first entity's generated key must be read before writing the second one. One solution to this problem is HiLo value generation: rather than relying on the database to generate each and every value, the application "allocates" a range of values, which it can then populate directly on new entities without any additional round-trips. When the range is exhausted, a new range is allocated. In practical terms, this uses a sequence that increments by some large value (100 by default), allowing the application to insert 100 rows autonomously. To use HiLo, specify `UseHiLo` on a property in your model's `OnModelCreating`: diff --git a/docs/modeling/indexes.md b/docs/modeling/indexes.md index 4ffc12052a..a8a971715c 100644 --- a/docs/modeling/indexes.md +++ b/docs/modeling/indexes.md @@ -24,6 +24,7 @@ CREATE INDEX "IX_Blog_Id" ON blogs ("Id") INCLUDE ("Name"); PostgreSQL supports a number of _index methods_, or _types_. These are specified at index creation time via the `USING _method_` clause, see the [PostgreSQL docs for `CREATE INDEX`](https://www.postgresql.org/docs/current/static/sql-createindex.html) and [this page](https://www.postgresql.org/docs/current/static/indexes-types.html) for information on the different types. The Npgsql EF Core provider allows you to specify the index method to be used by calling `HasMethod()` on your index in your context's `OnModelCreating` method: + ```c# protected override void OnModelCreating(ModelBuilder modelBuilder) => modelBuilder.Entity() diff --git a/docs/release-notes/2.0.md b/docs/release-notes/2.0.md index 32d433a8df..ddb19a8f5d 100644 --- a/docs/release-notes/2.0.md +++ b/docs/release-notes/2.0.md @@ -18,25 +18,23 @@ Here's the [full list of issues](https://github.com/npgsql/Npgsql.EntityFramewor * Previously an Npgsql.EntityFrameworkCore.PostgreSQL.Design nuget package existed alongside the main package. Its contents have been merged into the main Npgsql.EntityFrameworkCore.PostgreSQL and no new version has been released. * Specifying versions when specifying PostgreSQL extensions on your model is no longer supported - this was a very rarely-used feature which interfered with extension scaffolding. -## Contributors: +## Contributors Thank you very much to the following people who have contributed to the individual 2.0.x. releases. -### [Milestone 2.0.2](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.0.2): +### [Milestone 2.0.2](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.0.2) | Contributor | Assigned issues | | ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| | [@roji](https://github.com/roji) | [4](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.0.2+is%3Aclosed+assignee%3Aroji) | - -### [Milestone 2.0.1](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.0.1): +### [Milestone 2.0.1](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.0.1) | Contributor | Assigned issues | | ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| | [@roji](https://github.com/roji) | [5](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.0.1+is%3Aclosed+assignee%3Aroji) | - -### [Milestone 2.0.0](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.0.0): +### [Milestone 2.0.0](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.0.0) | Contributor | Assigned issues | | ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| diff --git a/docs/release-notes/2.1.md b/docs/release-notes/2.1.md index 71f10a786d..a5d0baf134 100644 --- a/docs/release-notes/2.1.md +++ b/docs/release-notes/2.1.md @@ -84,7 +84,7 @@ Here's the [full list of issues](https://github.com/npgsql/Npgsql.EntityFramewor Thank you very much to the following people who have contributed to the individual 2.1.x. releases. -### [Milestone 2.1.2](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.1.2): +### [Milestone 2.1.2](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.1.2) | Contributor | Assigned issues | | ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| @@ -92,29 +92,25 @@ Thank you very much to the following people who have contributed to the individu | [@austindrenski](https://github.com/austindrenski) | [3](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.1.2+is%3Aclosed+assignee%3Aaustindrenski) | | [@rwasef1830](https://github.com/rwasef1830) | [1](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.1.2+is%3Aclosed+assignee%3Arwasef1830) | - -### [Milestone 2.1.11](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.1.11): +### [Milestone 2.1.11](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.1.11) | Contributor | Assigned issues | | ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| | [@roji](https://github.com/roji) | [1](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.1.11+is%3Aclosed+assignee%3Aroji) | - -### [Milestone 2.1.1.1](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.1.1.1): +### [Milestone 2.1.1.1](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.1.1.1) | Contributor | Assigned issues | | ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| | [@roji](https://github.com/roji) | [4](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.1.1.1+is%3Aclosed+assignee%3Aroji) | - -### [Milestone 2.1.1](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.1.1): +### [Milestone 2.1.1](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.1.1) | Contributor | Assigned issues | | ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| | [@roji](https://github.com/roji) | [9](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.1.1+is%3Aclosed+assignee%3Aroji) | - -### [Milestone 2.1.0](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.1.0): +### [Milestone 2.1.0](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.1.0) | Contributor | Assigned issues | | ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| diff --git a/docs/release-notes/2.2.md b/docs/release-notes/2.2.md index 71378f5620..9fcd16fbe0 100644 --- a/docs/release-notes/2.2.md +++ b/docs/release-notes/2.2.md @@ -56,26 +56,24 @@ Thanks to [@khellang](https://github.com/khellang) for contributing this! The full list of issues for this release is [available here](https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL/issues?q=milestone%3A2.2.0+is%3Aclosed&utf8=%E2%9C%93). -## Contributors: +## Contributors Thank you very much to the following people who have contributed to the individual 2.2.x. releases. -### [Milestone 2.2.6](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.2.6): +### [Milestone 2.2.6](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.2.6) | Contributor | Assigned issues | | ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| | [@roji](https://github.com/roji) | [5](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.2.6+is%3Aclosed+assignee%3Aroji) | - -### [Milestone 2.2.4](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.2.4): +### [Milestone 2.2.4](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.2.4) | Contributor | Assigned issues | | ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| | [@roji](https://github.com/roji) | [3](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.2.4+is%3Aclosed+assignee%3Aroji) | | [@austindrenski](https://github.com/austindrenski) | [1](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.2.4+is%3Aclosed+assignee%3Aaustindrenski) | - -### [Milestone 2.2.0](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.2.0): +### [Milestone 2.2.0](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.2.0) | Contributor | Assigned issues | | ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| diff --git a/docs/release-notes/3.x.md b/docs/release-notes/3.x.md index b466fee4bd..7daf31eb30 100644 --- a/docs/release-notes/3.x.md +++ b/docs/release-notes/3.x.md @@ -48,61 +48,54 @@ protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) More information is available in [the page about generated properties](../modeling/generated-properties.md). -## Contributors: +## Contributors Thank you very much to the following people who have contributed to the individual 3.x releases. -### [Milestone 3.1.7](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.1.7): +### [Milestone 3.1.7](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.1.7) | Contributor | Assigned issues | | ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| | [@roji](https://github.com/roji) | [4](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.1.7+is%3Aclosed+assignee%3Aroji) | - -### [Milestone 3.1.4](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.1.4): +### [Milestone 3.1.4](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.1.4) | Contributor | Assigned issues | | ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| | [@roji](https://github.com/roji) | [4](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.1.4+is%3Aclosed+assignee%3Aroji) | - -### [Milestone 3.1.3](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.1.3): +### [Milestone 3.1.3](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.1.3) | Contributor | Assigned issues | | ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| | [@roji](https://github.com/roji) | [1](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.1.3+is%3Aclosed+assignee%3Aroji) | - -### [Milestone 3.1.2](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.1.2): +### [Milestone 3.1.2](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.1.2) | Contributor | Assigned issues | | ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| | [@roji](https://github.com/roji) | [3](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.1.2+is%3Aclosed+assignee%3Aroji) | | [@grzybsonssg](https://github.com/grzybsonssg) | [1](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.1.2+is%3Aclosed+assignee%3Agrzybsonssg) | - -### [Milestone 3.1.1.2](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.1.1.2): +### [Milestone 3.1.1.2](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.1.1.2) | Contributor | Assigned issues | | ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| | [@roji](https://github.com/roji) | [1](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.1.1.2+is%3Aclosed+assignee%3Aroji) | - -### [Milestone 3.1.1.1](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.1.1.1): +### [Milestone 3.1.1.1](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.1.1.1) | Contributor | Assigned issues | | ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| | [@roji](https://github.com/roji) | [1](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.1.1.1+is%3Aclosed+assignee%3Aroji) | - -### [Milestone 3.1.1](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.1.1): +### [Milestone 3.1.1](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.1.1) | Contributor | Assigned issues | | ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| | [@roji](https://github.com/roji) | [6](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.1.1+is%3Aclosed+assignee%3Aroji) | - -### [Milestone 3.1.0](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.1.0): +### [Milestone 3.1.0](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.1.0) | Contributor | Assigned issues | | ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| @@ -111,15 +104,13 @@ Thank you very much to the following people who have contributed to the individu | [@ins0mniaque](https://github.com/ins0mniaque) | [1](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.1.0+is%3Aclosed+assignee%3Ains0mniaque) | | [@MarioPrabowo](https://github.com/MarioPrabowo) | [1](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.1.0+is%3Aclosed+assignee%3AMarioPrabowo) | - -### [Milestone 3.0.1](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.0.1): +### [Milestone 3.0.1](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.0.1) | Contributor | Assigned issues | | ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| | [@roji](https://github.com/roji) | [1](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.0.1+is%3Aclosed+assignee%3Aroji) | - -### [Milestone 3.0.0](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.0.0): +### [Milestone 3.0.0](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.0.0) | Contributor | Assigned issues | | ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| From 565d8f2c78597bbd5779b1417625e75948cda13f Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Fri, 9 Oct 2020 16:16:53 +0300 Subject: [PATCH 034/207] Redo docs on operation translation Closes #56 --- docs/mapping/array.md | 27 +++--- docs/mapping/full-text-search.md | 32 +++---- docs/mapping/general.md | 17 ---- docs/mapping/json.md | 44 ++++----- docs/mapping/nts.md | 88 ++++++++--------- docs/mapping/range.md | 30 +++--- docs/mapping/translations.md | 156 +++++++++++++++++++++++++++++++ docs/toc.md | 1 + 8 files changed, 268 insertions(+), 127 deletions(-) create mode 100644 docs/mapping/translations.md diff --git a/docs/mapping/array.md b/docs/mapping/array.md index 2a93e46ab0..8883184fb3 100644 --- a/docs/mapping/array.md +++ b/docs/mapping/array.md @@ -7,7 +7,7 @@ PostgreSQL has the unique feature of supporting [*array data types*](https://www ## Mapping arrays -Simply define a regular .NET array or `List<>` property, and the provider +Simply define a regular .NET array or `List<>` property: ```c# public class Post @@ -19,19 +19,22 @@ public class Post } ``` -The provider will create `text[]` columns for the above two properties, and will properly detect changes in them - if you load an array and change one of its elements, calling `SaveChanges()` will automatically update the row in the database accordingly. +The provider will create `text[]` columns for the above two properties, and will properly detect changes in them - if you load an array and change one of its elements, calling `SaveChanges` will automatically update the row in the database accordingly. ## Operation translation The provider can also translate CLR array operations to the corresponding SQL operation; this allows you to efficiently work with arrays by evaluating operations in the database and avoids pulling all the data. The following table lists the range operations that currently get translated. If you run into a missing operation, please open an issue. -Note that operation translation on `List<>` is limited at this time, but will be improved in the future. It's recommended to use an array for now. - -| C# expression | SQL generated by Npgsql | -|-----------------------------------------------------------------|-------------------------| -| `.Where(c => c.SomeArray[1] == "foo")` | [`WHERE c."SomeArray"[1] = 'foo'`](https://www.postgresql.org/docs/current/static/arrays.html#ARRAYS-ACCESSING) -| `.Where(c => c.SomeArray.SequenceEqual(new[] { 1, 2, 3 })` | [`WHERE c."SomeArray" = ARRAY[1, 2, 3])`](https://www.postgresql.org/docs/current/static/arrays.html) -| `.Where(c => c.SomeArray.Contains(3))` | [`WHERE 3 = ANY(c."SomeArray")`](https://www.postgresql.org/docs/current/static/functions-comparisons.html#AEN21104) -| `.Where(c => c.SomeArray.Length == 3)` | [`WHERE cardinality(c."SomeArray") = 3`](https://www.postgresql.org/docs/current/static/functions-array.html#ARRAY-FUNCTIONS-TABLE) -| `.Where(c => c.SomeArray.Any(i => someOtherArray.Contains(i)))` | [`WHERE c."SomeArray" && @someOtherArray`](https://www.postgresql.org/docs/current/functions-array.html#ARRAY-OPERATORS-TABLE) -| `.Where(c => c.SomeArray.All(i => someOtherArray.Contains(i)))` | [`WHERE c."SomeArray" <@ @someOtherArray`](https://www.postgresql.org/docs/current/functions-array.html#ARRAY-OPERATORS-TABLE) +.NET | SQL +--------------------------------------------- | --- +array[1] | [array[1]](https://www.postgresql.org/docs/current/static/arrays.html#ARRAYS-ACCESSING) +array.Length | [cardinality(array)](https://www.postgresql.org/docs/current/static/functions-array.html#ARRAY-FUNCTIONS-TABLE) +array1.SequenceEqual(array2) | [array1 = array2](https://www.postgresql.org/docs/current/static/arrays.html) +array1.Contains(element)) | [element = ANY(array)](https://www.postgresql.org/docs/current/static/functions-comparisons.html#AEN21104) +array.Any() | [cardinality(array) > 0](https://www.postgresql.org/docs/current/static/functions-array.html#ARRAY-FUNCTIONS-TABLE) +array1.Any(i => array2.Contains(i)) | [array1 && array2](https://www.postgresql.org/docs/current/functions-array.html#ARRAY-OPERATORS-TABLE) +array1.All(i => array2.Contains(i)) | [array1 <@ array2](https://www.postgresql.org/docs/current/functions-array.html#ARRAY-OPERATORS-TABLE) +array.Any(s => EF.Functions.Like(string, s)) | [string = LIKE ANY (array)](https://www.postgresql.org/docs/current/functions-comparisons.html#id-1.5.8.30.16) +array.Any(s => EF.Functions.ILike(string, s)) | [string = ILIKE ANY (array)](https://www.postgresql.org/docs/current/functions-comparisons.html#id-1.5.8.30.16) +array.All(s => EF.Functions.Like(string, s)) | [string = LIKE ALL (array)](https://www.postgresql.org/docs/current/functions-comparisons.html#id-1.5.8.30.16) +array.All(s => EF.Functions.ILike(string, s)) | [string = ILIKE ALL (array)](https://www.postgresql.org/docs/current/functions-comparisons.html#id-1.5.8.30.16) diff --git a/docs/mapping/full-text-search.md b/docs/mapping/full-text-search.md index 329c3d6329..2344f0eab8 100644 --- a/docs/mapping/full-text-search.md +++ b/docs/mapping/full-text-search.md @@ -16,22 +16,6 @@ public class Product } ``` -## Operation translation - -Almost all PostgreSQL full text search functions can be called through LINQ queries. All supported EF Core LINQ methods are defined in extension classes in the `Microsoft.EntityFrameworkCore` namespace, so simply referencing the Npgsql provider will light up these methods. Here is a table showing translations for some operations; if an operation you need is missing, please open an issue to request for it. - -| This C# expression... | ... gets translated to this SQL | -|-----------------------------------------------------------------------------------------|---------------------------------------------------------------------| -| .Select(c => EF.Functions.ToTsVector("english", c.Name)) | [SELECT to_tsvector('english'::regconfig, c."Name")](https://www.postgresql.org/docs/current/static/textsearch-controls.html#TEXTSEARCH-PARSING-DOCUMENTS) -| .Select(c => NpgsqlTsVector.Parse("b")) | [SELECT CAST('b' AS tsvector)](https://www.postgresql.org/docs/current/static/sql-expressions.html#SQL-SYNTAX-TYPE-CASTS) -| .Select(c => EF.Functions.ToTsQuery("english", "pgsql")) | [SELECT to_tsquery('english'::regconfig, 'pgsql')`](https://www.postgresql.org/docs/current/static/textsearch-controls.html#TEXTSEARCH-PARSING-QUERIES) -| .Select(c => NpgsqlTsQuery.Parse("b")) | [SELECT CAST('b' AS tsquery)](https://www.postgresql.org/docs/current/static/sql-expressions.html#SQL-SYNTAX-TYPE-CASTS) -| .Where(c => c.SearchVector.Matches("Npgsql")) | [WHERE c."SearchVector" @@ 'Npgsql'](https://www.postgresql.org/docs/current/static/textsearch-intro.html#TEXTSEARCH-MATCHING) -| .Where(c => c.SearchVector.Matches(EF.Functions.ToTsQuery("Npgsql"))) | [WHERE c."SearchVector" @@ to_tsquery('Npgsql')](https://www.postgresql.org/docs/current/static/textsearch-controls.html#TEXTSEARCH-PARSING-QUERIES) -| .Select(c => EF.Functions.ToTsQuery(c.SearchQuery).ToNegative()) | [SELECT !! to_tsquery(c."SearchQuery")](https://www.postgresql.org/docs/current/static/textsearch-features.html#TEXTSEARCH-MANIPULATE-TSQUERY) -| .Select(c => EF.Functions.ToTsVector(c.Name).SetWeight(NpgsqlTsVector.Lexeme.Weight.A)) | [SELECT setweight(to_tsvector(c."Name"), 'A')](https://www.postgresql.org/docs/current/static/textsearch-features.html#TEXTSEARCH-MANIPULATE-TSVECTOR) -| .Where(c => c.SearchVector.Matches(EF.Functions.ToTsQuery("Npgsql")))
.OrderByDescending(c => c.SearchVector.Rank(EF.Functions.ToTsQuery("Npgsql"))) | WHERE (c."SearchVector" @@ to_tsquery('Npgsql'))
ORDER BY ts_rank(c."SearchVector", to_tsquery('Npgsql')) DESC - ## Setting up and querying a full text search index on an entity [As the PostgreSQL documentation explains](https://www.postgresql.org/docs/current/static/textsearch-tables.html), full-text search requires an index to run efficiently. This section will show two ways to do this, each having its benefits and drawbacks. Please read the PostgreSQL docs for more information on the two different approaches. @@ -159,3 +143,19 @@ var npgsql = context.Products .Matches("Npgsql")) .ToList(); ``` + +## Operation translation + +Almost all PostgreSQL full text search functions can be called through LINQ queries. All supported EF Core LINQ methods are defined in extension classes in the `Microsoft.EntityFrameworkCore` namespace, so simply referencing the Npgsql provider will light up these methods. Here is a table showing translations for some operations; if an operation you need is missing, please open an issue to request for it. + +C# | .NET +----------------------------------------------------------------------------|----- +EF.Functions.ToTsVector("english", string) | [to_tsvector('english'::regconfig, string)](https://www.postgresql.org/docs/current/static/textsearch-controls.html#TEXTSEARCH-PARSING-DOCUMENTS) +NpgsqlTsVector.Parse(string)) | [CAST(string AS tsvector)](https://www.postgresql.org/docs/current/static/sql-expressions.html#SQL-SYNTAX-TYPE-CASTS) +EF.Functions.ToTsQuery("english", queryString)) | [to_tsquery('english'::regconfig, queryString)](https://www.postgresql.org/docs/current/static/textsearch-controls.html#TEXTSEARCH-PARSING-QUERIES) +NpgsqlTsQuery.Parse(queryString)) | [CAST(queryString AS tsquery)](https://www.postgresql.org/docs/current/static/sql-expressions.html#SQL-SYNTAX-TYPE-CASTS) +tsVector.Matches(queryString)) | [tsVector @@ queryString](https://www.postgresql.org/docs/current/static/textsearch-intro.html#TEXTSEARCH-MATCHING) +tsVector.Matches(tsQuery) | [tsVector @@ tsQuery](https://www.postgresql.org/docs/current/static/textsearch-controls.html#TEXTSEARCH-PARSING-QUERIES) +tsQuery.ToNegative() | [!! tsQuery](https://www.postgresql.org/docs/current/static/textsearch-features.html#TEXTSEARCH-MANIPULATE-TSQUERY) +tsVector.SetWeight(NpgsqlTsVector.Lexeme.Weight.A)) | [setweight(tsVector, 'A')](https://www.postgresql.org/docs/current/static/textsearch-features.html#TEXTSEARCH-MANIPULATE-TSVECTOR) +tsVector.Rank(tsQuery) | [ts_rank(tsVector, tsQuery)](https://www.postgresql.org/docs/current/textsearch-controls.html#TEXTSEARCH-RANKING) diff --git a/docs/mapping/general.md b/docs/mapping/general.md index f3138f154b..706714e24a 100644 --- a/docs/mapping/general.md +++ b/docs/mapping/general.md @@ -39,20 +39,3 @@ builder.Entity() ``` *** - -## Operation translation to SQL - -Entity Framework Core allows providers to translate query expressions to SQL for database evaluation. For example, PostgreSQL supports [regular expression operations](http://www.postgresql.org/docs/current/static/functions-matching.html#FUNCTIONS-POSIX-REGEXP), and the Npgsql EF Core provider automatically translates .NET's `Regex.IsMatch()` to use this feature. Since evaluation happens at the server, table data doesn't need to be transferred to the client (saving bandwidth), and in some cases indexes can be used to speed things up. The same C# code on other providers will trigger client evaluation. - -Below are some Npgsql-specific translations, many additional standard ones are supported as well. See the other pages in the mapping section for more supported types and operations. - -| C# expression | SQL generated by Npgsql | -|------------------------------------------------------------|-------------------------| -| `.Where(c => Regex.IsMatch(c.Name, "^A+")` | [`WHERE "c"."Name" ~ '^A+'`](http://www.postgresql.org/docs/current/static/functions-matching.html#FUNCTIONS-POSIX-REGEXP) -| `.Where(c => EF.Functions.Like(c.Name, "foo%")` | [`WHERE "c"."Name" LIKE 'foo%'`](https://www.postgresql.org/docs/current/static/functions-matching.html#FUNCTIONS-LIKE) -| `.Where(c => EF.Functions.ILike(c.Name, "foo%")` | [`WHERE "c"."Name" ILIKE 'foo%'`](https://www.postgresql.org/docs/current/static/functions-matching.html#FUNCTIONS-LIKE) (case-insensitive LIKE) -| `.Select(c => EF.Functions.ToTsVector("english", c.Name))` | [`SELECT to_tsvector('english'::regconfig, "c"."Name")`](https://www.postgresql.org/docs/current/static/textsearch-controls.html#TEXTSEARCH-PARSING-DOCUMENTS) -| `.Select(c => EF.Functions.ToTsQuery("english", "pgsql"))` | [`SELECT to_tsquery('english'::regconfig, 'pgsql')`](https://www.postgresql.org/docs/current/static/textsearch-controls.html#TEXTSEARCH-PARSING-QUERIES) -| `.Where(c => c.SearchVector.Matches("Npgsql"))` | [`WHERE "c"."SearchVector" @@ 'Npgsql'`](https://www.postgresql.org/docs/current/static/textsearch-intro.html#TEXTSEARCH-MATCHING) -| `.Select(c => EF.Functions.ToTsQuery(c.SearchQuery).ToNegative())` | [`SELECT (!! to_tsquery("c"."SearchQuery"))`](https://www.postgresql.org/docs/current/static/textsearch-features.html#TEXTSEARCH-MANIPULATE-TSQUERY) -| `.Select(c => EF.Functions.ToTsVector(c.Name).SetWeight(NpgsqlTsVector.Lexeme.Weight.A))` | [`SELECT setweight(to_tsvector("c"."Name"), 'A')`](https://www.postgresql.org/docs/current/static/textsearch-features.html#TEXTSEARCH-MANIPULATE-TSVECTOR) diff --git a/docs/mapping/json.md b/docs/mapping/json.md index b2937578a2..301422060b 100644 --- a/docs/mapping/json.md +++ b/docs/mapping/json.md @@ -198,31 +198,31 @@ The following expression types and functions are translated: ### [POCO Mapping](#tab/poco) -| C# expression | SQL generated by Npgsql | -|-------------------------------------------------------------------------------------------|------------------------------| -| `.Where(e => e.Customer.Name == "Joe")` | [`WHERE "Customer"->>'Name' = 'Joe'`](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-OP-TABLE) -| `.Where(e => e.Customer.Orders[1].Price = 8)` | [`WHERE "Customer"#>>'{Orders,0,Price}'[1] = 8`](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-OP-TABLE) -| `.Where(e => e.Customer.Orders.Length == 2)` | [`WHERE jsonb_array_length("Customer"->'Orders' = 2`](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-PROCESSING-TABLE) -| `.Where(e => EF.Functions.JsonContains(e.Customer, @"{""Name"": ""Joe"", ""Age"": 25}")` | [`WHERE "Customer" @> '{"Name": "Joe", "Age": 25}'`](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) -| `.Where(e => EF.Functions.JsonContained(@"{""Name"": ""Joe"", ""Age"": 25}", e.Customer)` | [`WHERE '{"Name": "Joe", "Age": 25}' <@ "Customer"`](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) -| `.Where(e => EF.Functions.JsonExists(e.Customer, "Age")` | [`WHERE "Customer" ? 'Age'`](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) -| `.Where(e => EF.Functions.JsonExistsAny(e.Customer, "Age", "Address")` | [`WHERE "Customer" ?\| ARRAY['Age','Address']`](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) -| `.Where(e => EF.Functions.JsonExistsAll(e.Customer, "Age", "Address")` | [`WHERE "Customer" ?& ARRAY['Age','Address']`](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) -| `.Where(e => EF.Functions.JsonTypeof(e.Customer.Age) == "number")` | [`WHERE jsonb_typeof("Customer"->'Age') = 'number'`](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-PROCESSING-TABLE) +C# | .NET +----------------------------------------------------------------------------|----- +customer.Name | [customer->>'Name'](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-OP-TABLE) +customer.Orders[1].Price | [customer#>>'{Orders,0,Price}'[1]](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-OP-TABLE) +customer.Orders.Length | [jsonb_array_length(customer->'Orders')](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-PROCESSING-TABLE) +EF.Functions.JsonContains(customer, @"{""Name"": ""Joe"", ""Age"": 25}") | [customer @> '{"Name": "Joe", "Age": 25}'](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) +EF.Functions.JsonContained(@"{""Name"": ""Joe"", ""Age"": 25}", e.Customer) | ['{"Name": "Joe", "Age": 25}' <@ customer](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) +EF.Functions.JsonExists(e.Customer, "Age") | [customer ? 'Age'](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) +EF.Functions.JsonExistsAny(e.Customer, "Age", "Address") | [customer ?\| ARRAY['Age','Address']](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) +EF.Functions.JsonExistsAll(e.Customer, "Age", "Address") | [customer ?& ARRAY['Age','Address']](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) +EF.Functions.JsonTypeof(e.Customer.Age) | [jsonb_typeof(customer->'Age')](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-PROCESSING-TABLE) ### [JsonDocument Mapping](#tab/jsondocument) -| C# expression | SQL generated by Npgsql | -|-------------------------------------------------------------------------------------------|------------------------------| -| `.Where(e => e.Customer.GetProperty("Name").GetString() == "Joe")` | [`WHERE "Customer"->>'Name' = 'Joe'`](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-OP-TABLE) -| `.Where(e => e.Customer.GetProperty("Orders")[1].GetProperty("Price").GetInt32() = 8)` | [`WHERE "Customer"#>>'{Orders,0,Price}'[1] = 8`](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-OP-TABLE) -| `.Where(e => e.Customer.GetProperty("Orders").GetArrayLength() == 2)` | [`WHERE jsonb_array_length("Customer"->'Orders' = 2`](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-PROCESSING-TABLE) -| `.Where(e => EF.Functions.JsonContains(e.Customer, @"{""Name"": ""Joe"", ""Age"": 25}")` | [`WHERE "Customer" @> '{"Name": "Joe", "Age": 25}'`](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) -| `.Where(e => EF.Functions.JsonContained(@"{""Name"": ""Joe"", ""Age"": 25}", e.Customer)` | [`WHERE '{"Name": "Joe", "Age": 25}' <@ "Customer"`](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) -| `.Where(e => EF.Functions.JsonExists(e.Customer, "Age")` | [`WHERE "Customer" ? 'Age'`](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) -| `.Where(e => EF.Functions.JsonExistsAny(e.Customer, "Age", "Address")` | [`WHERE "Customer" ?\| ARRAY['Age','Address']`](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) -| `.Where(e => EF.Functions.JsonExistsAll(e.Customer, "Age", "Address")` | [`WHERE "Customer" ?& ARRAY['Age','Address']`](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) -| `.Where(e => EF.Functions.JsonTypeof(e.Customer.GetProperty("Age") == "number")` | [`WHERE jsonb_typeof("Customer"->'Age') = 'number'`](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-PROCESSING-TABLE) +C# | .NET +----------------------------------------------------------------------------|----- +customer.GetProperty("Name").GetString() | [customer->>'Name' = 'Joe'](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-OP-TABLE) +customer.GetProperty("Orders")[1].GetProperty("Price").GetInt32() | [customer#>>'{Orders,0,Price}'[1] = 8](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-OP-TABLE) +customer.GetProperty("Orders").GetArrayLength() | [jsonb_array_length(customer->'Orders'](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-PROCESSING-TABLE) +EF.Functions.JsonContains(customer, @"{""Name"": ""Joe"", ""Age"": 25}") | [customer @> '{"Name": "Joe", "Age": 25}'](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) +EF.Functions.JsonContained(@"{""Name"": ""Joe"", ""Age"": 25}", customer) | ['{"Name": "Joe", "Age": 25}' <@ customer](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) +EF.Functions.JsonExists(customer, "Age") | [customer ? 'Age'](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) +EF.Functions.JsonExistsAny(customer, "Age", "Address") | [customer ?\| ARRAY['Age','Address']](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) +EF.Functions.JsonExistsAll(customer, "Age", "Address") | [customer ?& ARRAY['Age','Address']](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) +EF.Functions.JsonTypeof(customer.GetProperty("Age") == "number") | [jsonb_typeof(customer->'Age') = 'number'](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-PROCESSING-TABLE) *** diff --git a/docs/mapping/nts.md b/docs/mapping/nts.md index abdbb17368..3bf31f2414 100644 --- a/docs/mapping/nts.md +++ b/docs/mapping/nts.md @@ -52,50 +52,6 @@ public Point Location { get; set; } This will constrain your column to XY points only. The same can be done via the fluent API with `HasColumnType()`. -## Operation translation - -The following table lists NetTopologySuite operations which are translated to PostGIS SQL operations. This allows you to use these NetTopologySuite methods and members efficiently - evaluation will happen on the server side. Since evaluation happens at the server, table data doesn't need to be transferred to the client (saving bandwidth), and in some cases indexes can be used to speed things up. - -Note that the plugin is far from covering all spatial operations. If an operation you need is missing, please open an issue to request for it. - -| This C# expression... | ... gets translated to this SQL | -|----------------------------------------------------------|---------------------------------| -| .Where(c => c.Polygon.Area() > x) | [WHERE ST_Area(c."Polygon") > x](https://postgis.net/docs/manual-2.4/ST_Area.html) -| .Where(c => c.Polygon.AsText() = x | [WHERE ST_AsText(c."Polygon") = x](https://postgis.net/docs/manual-2.4/ST_AsText.html) -| .Where(c => c.Polygon.Boundary = x | [WHERE ST_Boundary(c."Polygon") = x](https://postgis.net/docs/manual-2.4/ST_Boundary.html) -| .Where(c => c.Polygon.Contains(x)) | [WHERE ST_Contains(c."Polygon", x)](https://postgis.net/docs/manual-2.4/ST_Contains.html) -| .Where(c => c.Polygon.Covers(x)) | [WHERE ST_Covers(c."Polygon", x)](https://postgis.net/docs/manual-2.4/ST_Covers.html) -| .Where(c => c.Polygon.CoveredBy(x)) | [WHERE ST_CoveredBy(c."Polygon", x)](https://postgis.net/docs/manual-2.4/ST_CoveredBy.html) -| .Where(c => c.Polygon.Crosses(x)) | [WHERE ST_Crosses(c."Polygon", x)](https://postgis.net/docs/manual-2.4/ST_Crosses.html) -| .Where(c => c.Polygon.Difference(x) = y) | [WHERE ST_Difference(c."Polygon", x) = y](https://postgis.net/docs/manual-2.4/ST_Difference.html) -| .Where(c => c.Polygon.Disjoint(x)) | [WHERE ST_Disjoint(c."Polygon", x)](https://postgis.net/docs/manual-2.4/ST_Disjoint.html) -| .Where(c => c.Point.Distance(x) > y) | [WHERE ST_Distance(c."Polygon", x) > y](https://postgis.net/docs/manual-2.4/ST_Distance.html) -| .Where(c => c.Polygon.Equals(x)) | [WHERE c."Polygon" = x](https://postgis.net/docs/manual-2.4/ST_Geometry_EQ.html) -| .Where(c => c.Polygon.EqualsExact(x)) | [WHERE c."Polygon" = x](https://postgis.net/docs/manual-2.4/ST_Geometry_EQ.html) -| .Where(c => c.Polygon.EqualsTopologically(x)) | [WHERE ST_Equals(c."Polygon", x)](https://postgis.net/docs/manual-2.4/ST_Equals.html) -| .Where(c => c.Geometry.GeometryType() = x) | [WHERE GeometryType(c."GeomCollection") = x](https://postgis.net/docs/manual-2.4/GeometryType.html) -| .Where(c => c.GeomCollection.GetGeometryN(2) = x) | [WHERE ST_GeometryN(c."GeomCollection", 3) = x](https://postgis.net/docs/manual-2.4/ST_GeometryN.html) -| .Where(c => c.Polygon.Intersection(x) = y) | [WHERE ST_Intersection(c."Polygon", x) = y](https://postgis.net/docs/manual-2.4/ST_Intersection.html) -| .Where(c => c.Polygon.Intersects(x)) | [WHERE ST_Intersects(c."Polygon", x)](https://postgis.net/docs/manual-2.4/ST_Intersects.html) -| .Where(c => c.LineString.IsClosed()) | [WHERE ST_IsClosed(c."LineString")](https://postgis.net/docs/manual-2.4/ST_IsClosed.html) -| .Where(c => c.GeomCollection.IsEmpty()) | [WHERE ST_IsEmpty(c."GeomCollection")](https://postgis.net/docs/manual-2.4/ST_IsEmpty.html) -| .Where(c => c.Polygon.IsSimple()) | [WHERE ST_IsSimple(c."Polygon")](https://postgis.net/docs/manual-2.4/ST_IsSimple.html) -| .Where(c => c.Polygon.IsValid()) | [WHERE ST_IsValid(c."Polygon")](https://postgis.net/docs/manual-2.4/ST_IsValid.html) -| .Where(c => c.LineString.Length > x) | [WHERE ST_Length(c."LineString") > x](https://postgis.net/docs/manual-2.4/ST_Length.html) -| .Where(c => c.GeomCollection.NumGeometries > x) | [WHERE ST_NumGeometries(c."GeomCollection") > x](https://postgis.net/docs/manual-2.4/ST_NumGeometries.html) -| .Where(c => c.LineString.NumPoints > x) | [WHERE ST_NumPoints(c."LineString") > x](https://postgis.net/docs/manual-2.4/ST_NumPoints.html) -| .Where(c => c.Polygon.Overlaps(x)) | [WHERE ST_Overlaps(c."Polygon", x)](https://postgis.net/docs/manual-2.4/ST_Overlaps.html) -| .Where(c => c.Polygon.Relate(x) == y) | [WHERE ST_Relate(c."Polygon", x) = y](https://postgis.net/docs/manual-2.4/ST_Relate.html) -| .Where(c => c.LineString.Reverse() == x) | [WHERE ST_Reverse(c."Polygon") = x](https://postgis.net/docs/manual-2.4/ST_Reverse.html) -| .Where(c => c.Polygon.SymmetricDifference(x) == y) | [WHERE ST_SymDifference(c."Polygon", x) = y](https://postgis.net/docs/manual-2.4/ST_SymDifference.html) -| .Where(c => c.Polygon.Touches(x)) | [WHERE ST_Touches(c."Polygon", x)](https://postgis.net/docs/manual-2.4/ST_Touches.html) -| .Where(c => c.Polygon.ToText() = x) | [WHERE ST_AsText(c."Polygon") = x](https://postgis.net/docs/manual-2.4/ST_AsText.html) -| .Where(c => c.Polygon.Union(x) = y) | [WHERE ST_Union(c."Polygon", x) = y](https://postgis.net/docs/manual-2.4/ST_Union.html) -| .Where(c => c.Polygon.Within(x)) | [WHERE ST_Within(c."Polygon", x)](https://postgis.net/docs/manual-2.4/ST_Within.html) -| .Where(c => c.Point.X == 3) | [WHERE ST_X(c."Point") = 3](https://postgis.net/docs/manual-2.4/ST_X.html) -| .Where(c => c.Point.Y == 3) | [WHERE ST_Y(c."Point") = 3](https://postgis.net/docs/manual-2.4/ST_Y.html) -| .Where(c => c.Point.Z == 3) | [WHERE ST_Z(c."Point") = 3](https://postgis.net/docs/manual-2.4/ST_Z.html) - ## Geography (geodetic) support PostGIS has two types: `geometry` (for Cartesian coordinates) and `geography` (for geodetic or spherical coordinates). You can read about the geometry/geography distinction [in the PostGIS docs](https://postgis.net/docs/manual-2.4/using_postgis_dbmanagement.html#PostGIS_Geography) or in [this blog post](http://workshops.boundlessgeo.com/postgis-intro/geography.html). In a nutshell, `geography` is much more accurate when doing calculations over long distances, but is more expensive computationally and supports only a small subset of the spatial operations supported by `geometry`. @@ -122,3 +78,47 @@ public class City ``` Once you do this, your column will be created as `geography`, and spatial operations will behave as expected. + +## Operation translation + +The following table lists NetTopologySuite operations which are translated to PostGIS SQL operations. This allows you to use these NetTopologySuite methods and members efficiently - evaluation will happen on the server side. Since evaluation happens at the server, table data doesn't need to be transferred to the client (saving bandwidth), and in some cases indexes can be used to speed things up. + +Note that the plugin is far from covering all spatial operations. If an operation you need is missing, please open an issue to request for it. + +C# | .NET +---------------------------------|----- +geom.Area() | [ST_Area(geom)](https://postgis.net/docs/manual-3.0/ST_Area.html) +geom.AsText() | [ST_AsText(geom)](https://postgis.net/docs/manual-3.0/ST_AsText.html) +geom.Boundary | [ST_Boundary(geom)](https://postgis.net/docs/manual-3.0/ST_Boundary.html) +geom1.Contains(geom2)) | [ST_Contains(geom1, geom2)](https://postgis.net/docs/manual-3.0/ST_Contains.html) +geom1.Covers(geom2)) | [ST_Covers(geom1, geom2)](https://postgis.net/docs/manual-3.0/ST_Covers.html) +geom1.CoveredBy(geom2)) | [ST_CoveredBy(geom1, geom2)](https://postgis.net/docs/manual-3.0/ST_CoveredBy.html) +geom1.Crosses(geom2) | [ST_Crosses(geom1, geom2)](https://postgis.net/docs/manual-3.0/ST_Crosses.html) +geom1.Difference(geom2) | [ST_Difference(geom1, geom2)](https://postgis.net/docs/manual-3.0/ST_Difference.html) +geom1.Disjoint(geom2)) | [ST_Disjoint(geom1, geom2)](https://postgis.net/docs/manual-3.0/ST_Disjoint.html) +geom1.Distance(geom2) | [ST_Distance(geom1, geom2)](https://postgis.net/docs/manual-3.0/ST_Distance.html) +geom1.Equals(geom2) | [geom1 = geom2](https://postgis.net/docs/manual-3.0/ST_Geometry_EQ.html) +geom1.Polygon.EqualsExact(geom2) | [geom1 = geom2](https://postgis.net/docs/manual-3.0/ST_Geometry_EQ.html) +geom1.EqualsTopologically(geom2) | [ST_Equals(geom1, geom2)](https://postgis.net/docs/manual-3.0/ST_Equals.html) +geom.GeometryType() | [GeometryType(geom)](https://postgis.net/docs/manual-3.0/GeometryType.html) +geomCollection.GetGeometryN(i) | [ST_GeometryN(geomCollection, i)](https://postgis.net/docs/manual-3.0/ST_GeometryN.html) +geom1.Intersection(geom2) | [ST_Intersection(geom1, geom2)](https://postgis.net/docs/manual-3.0/ST_Intersection.html) +geom2.Intersects(geom2) | [ST_Intersects(geom1, geom2)](https://postgis.net/docs/manual-3.0/ST_Intersects.html) +lineString.IsClosed() | [ST_IsClosed(lineString)](https://postgis.net/docs/manual-3.0/ST_IsClosed.html) +geomCollection.IsEmpty() | [ST_IsEmpty(geomCollection)](https://postgis.net/docs/manual-3.0/ST_IsEmpty.html) +geom.IsSimple() | [ST_IsSimple(geom)](https://postgis.net/docs/manual-3.0/ST_IsSimple.html) +geom.IsValid() | [ST_IsValid(geom)](https://postgis.net/docs/manual-3.0/ST_IsValid.html) +lineString.Length | [ST_Length(lineString)](https://postgis.net/docs/manual-3.0/ST_Length.html) +geomCollection.NumGeometries | [ST_NumGeometries(geomCollection)](https://postgis.net/docs/manual-3.0/ST_NumGeometries.html) +lineString.NumPoints | [ST_NumPoints(lineString)](https://postgis.net/docs/manual-3.0/ST_NumPoints.html) +geom1.Overlaps(geom2)) | [ST_Overlaps(geom1, geom2)](https://postgis.net/docs/manual-3.0/ST_Overlaps.html) +geom1.Relate(geom2) | [ST_Relate(geom1, geom2)](https://postgis.net/docs/manual-3.0/ST_Relate.html) +geom.Reverse() | [ST_Reverse(geom)](https://postgis.net/docs/manual-3.0/ST_Reverse.html) +geom1.SymmetricDifference(geom2) | [ST_SymDifference(geom1, geom2)](https://postgis.net/docs/manual-3.0/ST_SymDifference.html) +geom1.Touches(geom2)) | [ST_Touches(geom1, geom2)](https://postgis.net/docs/manual-3.0/ST_Touches.html) +geom.ToText() | [ST_AsText(geom)](https://postgis.net/docs/manual-3.0/ST_AsText.html) +geom1.Union(geom2) | [ST_Union(geom1, geom2)](https://postgis.net/docs/manual-3.0/ST_Union.html) +geom1.Within(geom2) | [ST_Within(geom1, geom2)](https://postgis.net/docs/manual-3.0/ST_Within.html) +point.X | [ST_X(point)](https://postgis.net/docs/manual-3.0/ST_X.html) +point.Y | [ST_Y(point)](https://postgis.net/docs/manual-3.0/ST_Y.html) +point.Z | [ST_Z(point)](https://postgis.net/docs/manual-3.0/ST_Z.html) diff --git a/docs/mapping/range.md b/docs/mapping/range.md index e9f05e3d4e..a94c38c217 100644 --- a/docs/mapping/range.md +++ b/docs/mapping/range.md @@ -56,19 +56,17 @@ This will translate to an SQL operation using the PostgreSQL `@>` operator, eval The following table lists the range operations that currently get translated. If you run into a missing operation, please open an issue. -| C# expression | SQL generated by Npgsql | -|------------------------------------------------------------|-------------------------| -| `.Where(c => c.SomeRange.Contains(3))` | [`WHERE x."SomeRange" @> 3`](https://www.postgresql.org/docs/current/static/functions-range.html#RANGE-OPERATORS-TABLE) -| `.Where(c => c.SomeRange.Contains(otherRange))` | [`WHERE x."SomeRange" @> @__otherRange_0`](https://www.postgresql.org/docs/current/static/functions-range.html#RANGE-OPERATORS-TABLE) -| `.Where(c => c.SomeRange.ContainedBy(otherRange))` | [`WHERE x."SomeRange" <@ @__otherRange_0`](https://www.postgresql.org/docs/current/static/functions-range.html#RANGE-OPERATORS-TABLE) -| `.Where(c => c.SomeRange == otherRange)` | [`WHERE x."SomeRange" = @__otherRange_0`](https://www.postgresql.org/docs/current/static/functions-range.html#RANGE-OPERATORS-TABLE) -| `.Where(c => c.SomeRange != otherRange)` | [`WHERE x."SomeRange" <> @__otherRange_0`](https://www.postgresql.org/docs/current/static/functions-range.html#RANGE-OPERATORS-TABLE) -| `.Where(c => c.SomeRange.Overlaps(otherRange))` | [`WHERE x."SomeRange" && @__otherRange_0`](https://www.postgresql.org/docs/current/static/functions-range.html#RANGE-OPERATORS-TABLE) -| `.Where(c => c.SomeRange.IsStrictlyLeftOf(otherRange))` | [`WHERE x."SomeRange" << @__otherRange_0`](https://www.postgresql.org/docs/current/static/functions-range.html#RANGE-OPERATORS-TABLE) -| `.Where(c => c.SomeRange.IsStrictlyRightOf(otherRange))` | [`WHERE x."SomeRange" >> @__otherRange_0`](https://www.postgresql.org/docs/current/static/functions-range.html#RANGE-OPERATORS-TABLE) -| `.Where(c => c.SomeRange.DoesNotExtendLeftOf(otherRange))` | [`WHERE x."SomeRange" &> @__otherRange_0`](https://www.postgresql.org/docs/current/static/functions-range.html#RANGE-OPERATORS-TABLE) -| `.Where(c => c.SomeRange.DoesNotExtendRightOf(otherRange))`| [`WHERE x."SomeRange" <& @__otherRange_0`](https://www.postgresql.org/docs/current/static/functions-range.html#RANGE-OPERATORS-TABLE) -| `.Where(c => c.SomeRange.IsAdjacentTo(otherRange))` | [`WHERE x."SomeRange" -\|- @__otherRange_0`](https://www.postgresql.org/docs/current/static/functions-range.html#RANGE-OPERATORS-TABLE) -| `.Select(c => c.SomeRange.Union(otherRange))` | [`SELECT x."SomeRange" + @__otherRange_0`](https://www.postgresql.org/docs/current/static/functions-range.html#RANGE-OPERATORS-TABLE) -| `.Select(c => c.SomeRange.Intersect(otherRange))` | [`SELECT x."SomeRange" * @__otherRange_0`](https://www.postgresql.org/docs/current/static/functions-range.html#RANGE-OPERATORS-TABLE) -| `.Select(c => c.SomeRange.Except(otherRange))` | [`SELECT x."SomeRange" - @__otherRange_0`](https://www.postgresql.org/docs/current/static/functions-range.html#RANGE-OPERATORS-TABLE) +C# | .NET +----------------------------------------------------------------------------|----- +range.Contains(i) | [range @> 3](https://www.postgresql.org/docs/current/static/functions-range.html#RANGE-OPERATORS-TABLE) +range1.Contains(range2) | [range @> range2](https://www.postgresql.org/docs/current/static/functions-range.html#RANGE-OPERATORS-TABLE) +range1.ContainedBy(range2) | [range1 <@ range2](https://www.postgresql.org/docs/current/static/functions-range.html#RANGE-OPERATORS-TABLE) +range1.Overlaps(range2) | [range1 && range2](https://www.postgresql.org/docs/current/static/functions-range.html#RANGE-OPERATORS-TABLE) +range1.IsStrictlyLeftOf(range2) | [range1 << range2](https://www.postgresql.org/docs/current/static/functions-range.html#RANGE-OPERATORS-TABLE) +range1.IsStrictlyRightOf(range2) | [range1 >> range2](https://www.postgresql.org/docs/current/static/functions-range.html#RANGE-OPERATORS-TABLE) +range1.DoesNotExtendLeftOf(range2) | [range1 &> range2](https://www.postgresql.org/docs/current/static/functions-range.html#RANGE-OPERATORS-TABLE) +range1.DoesNotExtendRightOf(range2) | [range1 <& range2](https://www.postgresql.org/docs/current/static/functions-range.html#RANGE-OPERATORS-TABLE) +range1.IsAdjacentTo(range2) | [range1 -\|- range2](https://www.postgresql.org/docs/current/static/functions-range.html#RANGE-OPERATORS-TABLE) +range1.Union(range2) | [range1 + range2](https://www.postgresql.org/docs/current/static/functions-range.html#RANGE-OPERATORS-TABLE) +range1.Intersect(range2) | [range1 * range2](https://www.postgresql.org/docs/current/static/functions-range.html#RANGE-OPERATORS-TABLE) +range1.Except(range2) | [range1 - range2](https://www.postgresql.org/docs/current/static/functions-range.html#RANGE-OPERATORS-TABLE) diff --git a/docs/mapping/translations.md b/docs/mapping/translations.md new file mode 100644 index 0000000000..eee370204b --- /dev/null +++ b/docs/mapping/translations.md @@ -0,0 +1,156 @@ +# Translations + +Entity Framework Core allows providers to translate query expressions to SQL for database evaluation. For example, PostgreSQL supports [regular expression operations](http://www.postgresql.org/docs/current/static/functions-matching.html#FUNCTIONS-POSIX-REGEXP), and the Npgsql EF Core provider automatically translates .NET's [`Regex.IsMatch`](https://docs.microsoft.com/dotnet/api/system.text.regularexpressions.regex.ismatch) to use this feature. Since evaluation happens at the server, table data doesn't need to be transferred to the client (saving bandwidth), and in some cases indexes can be used to speed things up. The same C# code on other providers will trigger client evaluation. + +The Npgsql-specific translations are listed below. Some areas, such as [full-text search](full-text-search.md), have their own pages in this section which list additional translations. + +## Binary functions + +.NET | SQL | Added in +---------------------------- | ------------------------------- | -------- +bytes[i] | get_byte(bytes, i) | EF Core 5.0 +bytes.Contains(value) | position(value IN bytes) > 0 | EF Core 5.0 +bytes.Length | length(@bytes) | EF Core 5.0 +bytes1.SequenceEqual(bytes2) | @bytes = @second | EF Core 5.0 + +## Date and time functions + +.NET | SQL +------------------------------ | --- +DateTime.Now | [now()](https://www.postgresql.org/docs/current/functions-datetime.html) +DateTime.Today | [date_trunc('day', now())](https://www.postgresql.org/docs/current/functions-datetime.html) +DateTime.UtcNow | [now() AT TIME ZONE 'UTC'](https://www.postgresql.org/docs/current/functions-datetime.html) +dateTime.AddDays(1) | [dateTime + INTERVAL '1 days'](https://www.postgresql.org/docs/current/functions-datetime.html#OPERATORS-DATETIME-TABLE) +dateTime.AddHours(value) | [dateTime + INTERVAL '1 hours'](https://www.postgresql.org/docs/current/functions-datetime.html#OPERATORS-DATETIME-TABLE) +dateTime.AddMinutes(1) | [dateTime + INTERVAL '1 minutes'](https://www.postgresql.org/docs/current/functions-datetime.html#OPERATORS-DATETIME-TABLE) +dateTime.AddMonths(1) | [dateTime + INTERVAL '1 months'](https://www.postgresql.org/docs/current/functions-datetime.html#OPERATORS-DATETIME-TABLE) +dateTime.AddSeconds(1) | [dateTime + INTERVAL '1 seconds'](https://www.postgresql.org/docs/current/functions-datetime.html#OPERATORS-DATETIME-TABLE) +dateTime.AddYears(1) | [dateTime + INTERVAL '1 years'](https://www.postgresql.org/docs/current/functions-datetime.html#OPERATORS-DATETIME-TABLE) +dateTime.Date | [date_trunc('day', dateTime)](https://www.postgresql.org/docs/current/functions-datetime.html) +dateTime.Day | [date_part('day', dateTime)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) +dateTime.DayOfWeek | [floor(date_part('dow', o.""OrderDate""))::INT](https://www.postgresql.org/docs/current/functions-datetime.html) +dateTime.DayOfYear | [date_part('doy', dateTime)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) +dateTime.Hour | [date_part('hour', dateTime)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) +dateTime.Minute | [date_part('minute', dateTime)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) +dateTime.Month | [date_part('month', dateTime)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) +dateTime.Second | [date_part('second', dateTime)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) +dateTime.Year | [date_part('year', dateTime)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) +timeSpan.Days | [floor(date_part('day', timeSpan))::INT](https://www.postgresql.org/docs/current/functions-datetime.html) +timeSpan.Hours | [floor(date_part('hour', timeSpan))::INT](https://www.postgresql.org/docs/current/functions-datetime.html) +timeSpan.Minutes | [floor(date_part('minute', timeSpan))::INT](https://www.postgresql.org/docs/current/functions-datetime.html) +timeSpan.Seconds | [floor(date_part('second', timeSpan))::INT](https://www.postgresql.org/docs/current/functions-datetime.html) +timeSpan.Milliseconds | [floor(date_part('millisecond', timeSpan))::INT](https://www.postgresql.org/docs/current/functions-datetime.html) +timeSpan.Milliseconds | [floor(date_part('millisecond', timeSpan))::INT](https://www.postgresql.org/docs/current/functions-datetime.html) +dateTime1 - dateTime2 | [dateTime1 - dateTime2](https://www.postgresql.org/docs/current/functions-datetime.html#OPERATORS-DATETIME-TABLE) +new DateTime(year, month, day) | [make_date(year, month, day)](https://www.postgresql.org/docs/current/functions-datetime.html) +new DateTime(y, m, d, h, m, s) | [make_timestamp(y, m, d, h, m, s)](https://www.postgresql.org/docs/current/functions-datetime.html) + +## Network functions + +.NET | SQL +------------------------------------------------ | --- +IPAddress.Parse(string) | [CAST(string AS inet)](https://www.postgresql.org/docs/current/datatype-net-types.html#DATATYPE-INET) +PhysicalAddress.Parse(string) | [CAST(string AS macaddr)](https://www.postgresql.org/docs/current/datatype-net-types.html#DATATYPE-MACADDR) +EF.Functions.LessThan(net1, net2) | [net1 < net2](https://www.postgresql.org/docs/current/functions-net.html#CIDR-INET-OPERATORS-TABLE) +EF.Functions.LessThanOrEqual(net1, net2) | [net1 <= net2](https://www.postgresql.org/docs/current/functions-net.html#CIDR-INET-OPERATORS-TABLE) +EF.Functions.GreaterThan(net1, net2) | [net1 > net2](https://www.postgresql.org/docs/current/functions-net.html#CIDR-INET-OPERATORS-TABLE) +EF.Functions.GreaterThanOrEqual(net1, net2) | [net1 >= net2](https://www.postgresql.org/docs/current/functions-net.html#CIDR-INET-OPERATORS-TABLE) +EF.Functions.ContainedBy(inet1, inet2) | [inet1 << inet2](https://www.postgresql.org/docs/current/functions-net.html#CIDR-INET-OPERATORS-TABLE) +EF.Functions.ContainedByOrEqual(inet1, inet2) | [inet1 <<= inet2](https://www.postgresql.org/docs/current/functions-net.html#CIDR-INET-OPERATORS-TABLE) +EF.Functions.Contains(inet1, inet2) | [inet1 >> inet2](https://www.postgresql.org/docs/current/functions-net.html#CIDR-INET-OPERATORS-TABLE) +EF.Functions.ContainsOrEqual(inet1, inet2) | [inet1 >>= inet2](https://www.postgresql.org/docs/current/functions-net.html#CIDR-INET-OPERATORS-TABLE) +EF.Functions.ContainsOrContainedBy(inet1, inet2) | [inet1 && inet2](https://www.postgresql.org/docs/current/functions-net.html#CIDR-INET-OPERATORS-TABLE) +EF.Functions.BitwiseNot(net) | [~net1](https://www.postgresql.org/docs/current/functions-net.html#CIDR-INET-OPERATORS-TABLE) +EF.Functions.BitwiseAnd(net1, net2) | [net1 & net2](https://www.postgresql.org/docs/current/functions-net.html#CIDR-INET-OPERATORS-TABLE) +EF.Functions.BitwiseOr(net1, net2) | [net1 \| net2](https://www.postgresql.org/docs/current/functions-net.html#CIDR-INET-OPERATORS-TABLE) +EF.Functions.Add(inet, int) | [inet + int](https://www.postgresql.org/docs/current/functions-net.html#CIDR-INET-OPERATORS-TABLE) +EF.Functions.Subtract(inet, int) | [inet - int](https://www.postgresql.org/docs/current/functions-net.html#CIDR-INET-OPERATORS-TABLE) +EF.Functions.Subtract(inet1, inet2) | [inet1 - inet2](https://www.postgresql.org/docs/current/functions-net.html#CIDR-INET-OPERATORS-TABLE) +EF.Functions.Abbreviate(inet) | [abbrev(inet)](https://www.postgresql.org/docs/current/functions-net.html#CIDR-INET-FUNCTIONS-TABLE) +EF.Functions.Broadcast(inet) | [broadcast(inet)](https://www.postgresql.org/docs/current/functions-net.html#CIDR-INET-FUNCTIONS-TABLE) +EF.Functions.Family(inet) | [family(inet)](https://www.postgresql.org/docs/current/functions-net.html#CIDR-INET-FUNCTIONS-TABLE) +EF.Functions.Host(inet) | [host(inet)](https://www.postgresql.org/docs/current/functions-net.html#CIDR-INET-FUNCTIONS-TABLE) +EF.Functions.HostMark(inet) | [hostmask(inet)](https://www.postgresql.org/docs/current/functions-net.html#CIDR-INET-FUNCTIONS-TABLE) +EF.Functions.MaskLength(inet) | [masklen(inet)](https://www.postgresql.org/docs/current/functions-net.html#CIDR-INET-FUNCTIONS-TABLE) +EF.Functions.Netmask(inet) | [netmask(inet)](https://www.postgresql.org/docs/current/functions-net.html#CIDR-INET-FUNCTIONS-TABLE) +EF.Functions.Network(inet) | [network(inet)](https://www.postgresql.org/docs/current/functions-net.html#CIDR-INET-FUNCTIONS-TABLE) +EF.Functions.SetMaskLength(inet) | [set_masklen(inet)](https://www.postgresql.org/docs/current/functions-net.html#CIDR-INET-FUNCTIONS-TABLE) +EF.Functions.Text(inet) | [text(inet)](https://www.postgresql.org/docs/current/functions-net.html#CIDR-INET-FUNCTIONS-TABLE) +EF.Functions.SameFamily(inet1, inet2) | [inet_same_family(inet1, inet2)](https://www.postgresql.org/docs/current/functions-net.html#CIDR-INET-FUNCTIONS-TABLE) +EF.Functions.Merge(inet1, inet2) | [inet_merge(inet1, inet2)](https://www.postgresql.org/docs/current/functions-net.html#CIDR-INET-FUNCTIONS-TABLE) +EF.Functions.Truncate(macaddr) | [trunc(macaddr)](https://www.postgresql.org/docs/current/functions-net.html#CIDR-INET-FUNCTIONS-TABLE) +EF.Functions.Set7BitMac8(macaddr8) | [macaddr8_set7bit(macaddr8)](https://www.postgresql.org/docs/current/functions-net.html#CIDR-INET-FUNCTIONS-TABLE) + +## Numeric functions + +.NET | SQL +----------------------- | -------------------- +Math.Abs(value) | abs(value) +Math.Acos(d) | acos(d) +Math.Asin(d) | asin(d) +Math.Atan(d) | atan(d) +Math.Atan2(y, x) | atan2(y, x) +Math.Ceiling(d) | ceiling(d) +Math.Cos(d) | cos(d) +Math.Exp(d) | exp(d) +Math.Floor(d) | floor(d) +Math.Log(d) | ln(d) +Math.Log10(d) | log(d) +Math.Max(x, y) | greatest(x, y) +Math.Min(x, y) | least(x, y) +Math.Pow(x, y) | power(x, y) +Math.Round(d) | round(d) +Math.Round(d, decimals) | round(d, decimals) +Math.Sin(a) | sin(a) +Math.Sign(value) | sign(value)::int +Math.Sqrt(d) | sqrt(d) +Math.Tan(a) | tan(a) +Math.Truncate(d) | trunc(d) + +## String functions + +.NET | SQL | Added in +------------------------------------------------------------- | ------------------------------------------------------ | -------- +EF.Functions.Collate(operand, collation) | operand COLLATE collation | EF Core 5.0 +EF.Functions.Like(matchExpression, pattern) | matchExpression LIKE pattern +EF.Functions.Like(matchExpression, pattern, escapeCharacter) | matchExpression LIKE pattern ESCAPE escapeCharacter +EF.Functions.ILike(matchExpression, pattern) | [matchExpression ILIKE pattern](../misc/collations-and-case-sensitivity.md) +EF.Functions.ILike(matchExpression, pattern, escapeCharacter) | [matchExpression ILIKE pattern ESCAPE escapeCharacter](../misc/collations-and-case-sensitivity.md) +string.Compare(strA, strB) | CASE WHEN strA = strB THEN 0 ... END +string.Concat(str0, str1) | str0 \|\| str1 +string.IsNullOrEmpty(value) | value IS NULL OR value = '' +string.IsNullOrWhiteSpace(value) | value IS NULL OR btrim(value, E' \t\n\r') = '' +stringValue.CompareTo(strB) | CASE WHEN stringValue = strB THEN 0 ... END +stringValue.Contains(value) | strpos(stringValue, value) > 0 +stringValue.EndsWith(value) | stringValue LIKE '%' \|\| value +stringValue.FirstOrDefault() | substr(stringValue, 1, 1) | EF Core 5.0 +stringValue.IndexOf(value) | strpos(stringValue, value) - 1 +stringValue.LastOrDefault() | substr(stringValue, length(stringValue), 1) | EF Core 5.0 +stringValue.Length | length(stringValue) +stringValue.PadLeft(length) | lpad(stringValue, length) +stringValue.PadLeft(length, char) | lpad(stringValue, length, char) +stringValue.PadRight(length) | rpad(stringValue, length) +stringValue.PadRight(length, char) | rpad(stringValue, length, char) +stringValue.Replace(oldValue, newValue) | replace(stringValue, oldValue, newValue) +stringValue.StartsWith(value) | stringValue LIKE value \|\| '%' +stringValue.Substring(startIndex, length) | substr(stringValue, startIndex + 1, @length) +stringValue.ToLower() | lower(stringValue) +stringValue.ToUpper() | upper(stringValue) +stringValue.Trim() | btrim(stringValue) +stringValue.Trim(trimChar) | btrim(stringValue, trimChar) +stringValue.TrimEnd() | rtrim(stringValue) +stringValue.TrimEnd(trimChar) | rtrim(stringValue, trimChar) +stringValue.TrimStart() | ltrim(stringValue) +stringValue.TrimStart(trimChar) | ltrim(stringValue, trimChar) +EF.Functions.Reverse(value) | reverse(value) +Regex.IsMatch(stringValue, "^A+") | [stringValue ~ '^A+'](http://www.postgresql.org/docs/current/static/functions-matching.html#FUNCTIONS-POSIX-REGEXP) (with options) +Regex.IsMatch(stringValue, "^A+", regexOptions) | [stringValue ~ '^A+'](http://www.postgresql.org/docs/current/static/functions-matching.html#FUNCTIONS-POSIX-REGEXP) (with options) + +## Miscellaneous functions + +.NET | SQL +---------------------------------------- | -------------------- +collection.Contains(item) | item IN collection +enumValue.HasFlag(flag) | enumValue & flag = flag +nullable.GetValueOrDefault() | coalesce(nullable, 0) +nullable.GetValueOrDefault(defaultValue) | coalesce(nullable, defaultValue) \ No newline at end of file diff --git a/docs/toc.md b/docs/toc.md index a4522e3aed..a742d01f75 100644 --- a/docs/toc.md +++ b/docs/toc.md @@ -12,6 +12,7 @@ ## [Indexes](modeling/indexes.md) # Mapping and Translation ## [General](mapping/general.md) +## [Translations](mapping/translations.md) ## [JSON](mapping/json.md) ## [Spatial Data](mapping/nts.md) ## [Full Text Search](mapping/full-text-search.md) From dfb4d851d73c3c3d5f554016f174a8e2e48ac8b6 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Fri, 9 Oct 2020 16:57:51 +0300 Subject: [PATCH 035/207] Add Guid.NewGuid --- docs/mapping/translations.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/mapping/translations.md b/docs/mapping/translations.md index eee370204b..c928d86fee 100644 --- a/docs/mapping/translations.md +++ b/docs/mapping/translations.md @@ -152,5 +152,6 @@ Regex.IsMatch(stringValue, "^A+", regexOptions) | [stringValue ~ ' ---------------------------------------- | -------------------- collection.Contains(item) | item IN collection enumValue.HasFlag(flag) | enumValue & flag = flag +Guid.NewGuid() | [uuid_generate_v4()](https://www.postgresql.org/docs/current/uuid-ossp.html), or [gen_random_uuid()](https://www.postgresql.org/docs/current/functions-uuid.html) on PostgreSQL 13 with EF Core 5 and above. nullable.GetValueOrDefault() | coalesce(nullable, 0) -nullable.GetValueOrDefault(defaultValue) | coalesce(nullable, defaultValue) \ No newline at end of file +nullable.GetValueOrDefault(defaultValue) | coalesce(nullable, defaultValue) From 59ca253bb8a653cc592f39a3555add0687d2c412 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Fri, 9 Oct 2020 17:28:14 +0300 Subject: [PATCH 036/207] Corrected some table titles --- docs/mapping/full-text-search.md | 2 +- docs/mapping/json.md | 4 ++-- docs/mapping/nts.md | 2 +- docs/mapping/range.md | 4 ++-- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/docs/mapping/full-text-search.md b/docs/mapping/full-text-search.md index 2344f0eab8..a0f7296e21 100644 --- a/docs/mapping/full-text-search.md +++ b/docs/mapping/full-text-search.md @@ -148,7 +148,7 @@ var npgsql = context.Products Almost all PostgreSQL full text search functions can be called through LINQ queries. All supported EF Core LINQ methods are defined in extension classes in the `Microsoft.EntityFrameworkCore` namespace, so simply referencing the Npgsql provider will light up these methods. Here is a table showing translations for some operations; if an operation you need is missing, please open an issue to request for it. -C# | .NET +.NET | SQL ----------------------------------------------------------------------------|----- EF.Functions.ToTsVector("english", string) | [to_tsvector('english'::regconfig, string)](https://www.postgresql.org/docs/current/static/textsearch-controls.html#TEXTSEARCH-PARSING-DOCUMENTS) NpgsqlTsVector.Parse(string)) | [CAST(string AS tsvector)](https://www.postgresql.org/docs/current/static/sql-expressions.html#SQL-SYNTAX-TYPE-CASTS) diff --git a/docs/mapping/json.md b/docs/mapping/json.md index 301422060b..f4f11802e8 100644 --- a/docs/mapping/json.md +++ b/docs/mapping/json.md @@ -198,7 +198,7 @@ The following expression types and functions are translated: ### [POCO Mapping](#tab/poco) -C# | .NET +.NET | SQL ----------------------------------------------------------------------------|----- customer.Name | [customer->>'Name'](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-OP-TABLE) customer.Orders[1].Price | [customer#>>'{Orders,0,Price}'[1]](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-OP-TABLE) @@ -212,7 +212,7 @@ EF.Functions.JsonTypeof(e.Customer.Age) | [j ### [JsonDocument Mapping](#tab/jsondocument) -C# | .NET +.NET | SQL ----------------------------------------------------------------------------|----- customer.GetProperty("Name").GetString() | [customer->>'Name' = 'Joe'](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-OP-TABLE) customer.GetProperty("Orders")[1].GetProperty("Price").GetInt32() | [customer#>>'{Orders,0,Price}'[1] = 8](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-OP-TABLE) diff --git a/docs/mapping/nts.md b/docs/mapping/nts.md index 3bf31f2414..eeb27997f4 100644 --- a/docs/mapping/nts.md +++ b/docs/mapping/nts.md @@ -85,7 +85,7 @@ The following table lists NetTopologySuite operations which are translated to Po Note that the plugin is far from covering all spatial operations. If an operation you need is missing, please open an issue to request for it. -C# | .NET +.NET | SQL ---------------------------------|----- geom.Area() | [ST_Area(geom)](https://postgis.net/docs/manual-3.0/ST_Area.html) geom.AsText() | [ST_AsText(geom)](https://postgis.net/docs/manual-3.0/ST_AsText.html) diff --git a/docs/mapping/range.md b/docs/mapping/range.md index a94c38c217..1c8ae90b5f 100644 --- a/docs/mapping/range.md +++ b/docs/mapping/range.md @@ -56,8 +56,8 @@ This will translate to an SQL operation using the PostgreSQL `@>` operator, eval The following table lists the range operations that currently get translated. If you run into a missing operation, please open an issue. -C# | .NET -----------------------------------------------------------------------------|----- +.NET | SQL +--------------------------------------|----- range.Contains(i) | [range @> 3](https://www.postgresql.org/docs/current/static/functions-range.html#RANGE-OPERATORS-TABLE) range1.Contains(range2) | [range @> range2](https://www.postgresql.org/docs/current/static/functions-range.html#RANGE-OPERATORS-TABLE) range1.ContainedBy(range2) | [range1 <@ range2](https://www.postgresql.org/docs/current/static/functions-range.html#RANGE-OPERATORS-TABLE) From 16ba5543ed0954387b14cb1129079d547d96dd22 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Sun, 11 Oct 2020 12:43:34 +0300 Subject: [PATCH 037/207] Document unaccent --- docs/mapping/full-text-search.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/mapping/full-text-search.md b/docs/mapping/full-text-search.md index a0f7296e21..435541f41c 100644 --- a/docs/mapping/full-text-search.md +++ b/docs/mapping/full-text-search.md @@ -159,3 +159,5 @@ tsVector.Matches(tsQuery) | [t tsQuery.ToNegative() | [!! tsQuery](https://www.postgresql.org/docs/current/static/textsearch-features.html#TEXTSEARCH-MANIPULATE-TSQUERY) tsVector.SetWeight(NpgsqlTsVector.Lexeme.Weight.A)) | [setweight(tsVector, 'A')](https://www.postgresql.org/docs/current/static/textsearch-features.html#TEXTSEARCH-MANIPULATE-TSVECTOR) tsVector.Rank(tsQuery) | [ts_rank(tsVector, tsQuery)](https://www.postgresql.org/docs/current/textsearch-controls.html#TEXTSEARCH-RANKING) +EF.Functions.Unaccent(string) | [unaccent(string)](https://www.postgresql.org/docs/current/unaccent.html) +EF.Functions.Unaccent(regdictionary, string) | [unaccent(regdictionary, string)](https://www.postgresql.org/docs/current/unaccent.html) From 6b043a95b9f3be99841ca20a7b1d21426425feec Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Thu, 15 Oct 2020 12:23:09 +0300 Subject: [PATCH 038/207] Various linter and formatting fixes --- docs/index.md | 4 +- docs/mapping/enum.md | 1 - docs/mapping/full-text-search.md | 2 +- docs/mapping/nodatime.md | 2 +- docs/misc/other.md | 2 - docs/release-notes/1.1.md | 21 +++++----- docs/release-notes/2.0.md | 20 ++++----- docs/release-notes/2.1.md | 42 +++++++++---------- docs/release-notes/2.2.md | 22 +++++----- docs/release-notes/3.x.md | 72 ++++++++++++++++---------------- docs/toc.md | 27 ------------ docs/toc.yml | 54 ++++++++++++++++++++++++ 12 files changed, 146 insertions(+), 123 deletions(-) delete mode 100644 docs/toc.md create mode 100644 docs/toc.yml diff --git a/docs/index.md b/docs/index.md index c3ae340557..fb43b708c3 100644 --- a/docs/index.md +++ b/docs/index.md @@ -1,11 +1,11 @@ +# Npgsql Entity Framework Core Provider + [![stable](https://img.shields.io/nuget/v/Npgsql.EntityFrameworkCore.PostgreSQL.svg?label=stable)](https://www.nuget.org/packages/Npgsql.EntityFrameworkCore.PostgreSQL/) [![unstable](https://img.shields.io/myget/npgsql-unstable/vpre/Npgsql.EntityFrameworkCore.PostgreSQL.svg?label=unstable)](https://www.myget.org/feed/npgsql-unstable/package/nuget/Npgsql.EntityFrameworkCore.PostgreSQL) [![next patch](https://img.shields.io/myget/npgsql/v/Npgsql.EntityFrameworkCore.PostgreSQL.svg?label=next%20patch)](https://www.myget.org/feed/npgsql/package/nuget/Npgsql.EntityFrameworkCore.PostgreSQL) [![build](https://img.shields.io/github/workflow/status/npgsql/efcore.pg/Build)](https://github.com/npgsql/efcore.pg/actions) [![gitter](https://img.shields.io/badge/gitter-join%20chat-brightgreen.svg)](https://gitter.im/npgsql/npgsql) -# 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](https://docs.microsoft.com/ef/core/index) 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](https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL) repository, all issues should be reported there. diff --git a/docs/mapping/enum.md b/docs/mapping/enum.md index 13cee4e3c1..c1776e2938 100644 --- a/docs/mapping/enum.md +++ b/docs/mapping/enum.md @@ -82,4 +82,3 @@ Although PostgreSQL allows [altering enum types](https://www.postgresql.org/docs If you're creating your model from an existing database, the provider will recognize enums in your database, and scaffold the appropriate `HasPostgresEnum()` lines in your model. However, since the scaffolding process has no knowledge of your CLR type, and will therefore skip your enum columns (warnings will be logged). You will have to create the CLR type, add the global mapping and add the properties to your entities. In the future it may be possible to scaffold the actual enum type (and with it the properties), but this doesn't happen at the moment. - diff --git a/docs/mapping/full-text-search.md b/docs/mapping/full-text-search.md index 435541f41c..39e4923fef 100644 --- a/docs/mapping/full-text-search.md +++ b/docs/mapping/full-text-search.md @@ -34,7 +34,7 @@ public class Product } ``` -Setting up the column to be auto-updated depends on your PostgreSQL version. On PostgreSQL 12 and above, the column can be a simple [generated column](../modeling/generated-properties##computed-columns-on-add-or-update), and version 5.0.0 contains sugar for setting that up. In previous versions, you must manually set up database triggers that update the column instead. +Setting up the column to be auto-updated depends on your PostgreSQL version. On PostgreSQL 12 and above, the column can be a simple [generated column](../modeling/generated-properties#computed-columns-on-add-or-update), and version 5.0.0 contains sugar for setting that up. In previous versions, you must manually set up database triggers that update the column instead. #### [PostgreSQL 12+](#tab/pg12) diff --git a/docs/mapping/nodatime.md b/docs/mapping/nodatime.md index 2f72b730c4..aef0f714aa 100644 --- a/docs/mapping/nodatime.md +++ b/docs/mapping/nodatime.md @@ -1,6 +1,6 @@ # Date/Time Mapping with NodaTime -## What is NodaTime? +## What is NodaTime By default, [the PostgreSQL date/time types](https://www.postgresql.org/docs/current/static/datatype-datetime.html) are mapped to the built-in .NET types (`DateTime`, `TimeSpan`). Unfortunately, these built-in types are flawed in many ways. The [NodaTime library](http://nodatime.org/) was created to solve many of these problems, and if your application handles dates and times in anything but the most basic way, you should consider using it. To learn more [read this blog post by Jon Skeet](http://blog.nodatime.org/2011/08/what-wrong-with-datetime-anyway.html). diff --git a/docs/misc/other.md b/docs/misc/other.md index c9e9038e15..2e06eaef7f 100644 --- a/docs/misc/other.md +++ b/docs/misc/other.md @@ -63,5 +63,3 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) typeof(ParentEntityType), new List { "prefix_column_1", "prefix_column_2" }); ``` - - diff --git a/docs/release-notes/1.1.md b/docs/release-notes/1.1.md index 55efa5e15e..39d0628e81 100644 --- a/docs/release-notes/1.1.md +++ b/docs/release-notes/1.1.md @@ -17,7 +17,7 @@ Aside from general EF Core features, version 1.1.0 of the Npgsql provider contai * Optimistic concurrency with PostgreSQL's xmin column ([#19](https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL/issues/19)). Simply specify `.UseXminAsConcurrencyToken()` on an entity to start using this, see the [EF docs for more details](https://docs.efproject.net/en/latest/modeling/concurrency.html). * Cleanup of how serial (autoincrement) and generated GUID/UUID columns are managed. -Here's the [full list of issues](https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL/milestone/3?closed=1). Please report any problems to https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL. +Here's the [full list of issues](https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL/milestone/3?closed=1). Please report any problems to . ## Upgrading from 1.0.x @@ -29,19 +29,18 @@ Unfortunately, this change will cause some incorrect changes the first time you Apologies for this problematic upgrade procedure, it should at least keep things clean going forward. -## Contributors: +## Contributors Thank you very much to the following people who have contributed to the individual 1.1.x. releases. -### [Milestone 1.1.1](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A1.1.1): +### [Milestone 1.1.1](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A1.1.1) -| Contributor | Assigned issues | -| ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| -| [@roji](https://github.com/roji) | [8](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A1.1.1+is%3Aclosed+assignee%3Aroji) | +Contributor | Assigned issues +-------------------------------- | ---------------:| +[@roji](https://github.com/roji) | [8](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A1.1.1+is%3Aclosed+assignee%3Aroji) +### [Milestone 1.1.0](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A1.1.0) -### [Milestone 1.1.0](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A1.1.0): - -| Contributor | Assigned issues | -| ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| -| [@roji](https://github.com/roji) | [11](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A1.1.0+is%3Aclosed+assignee%3Aroji) | +Contributor | Assigned issues +-------------------------------- | ---------------:| +[@roji](https://github.com/roji) | [11](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A1.1.0+is%3Aclosed+assignee%3Aroji) diff --git a/docs/release-notes/2.0.md b/docs/release-notes/2.0.md index ddb19a8f5d..12b70b01a8 100644 --- a/docs/release-notes/2.0.md +++ b/docs/release-notes/2.0.md @@ -11,7 +11,7 @@ Aside from general EF Core features new in 2.0.0, the Npgsql provider contains t * PostgreSQL extensions are now included in scaffolded models ([#102](https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL/issues/102)). * More LINQ operations are translated to SQL, and more database scenarios are scaffolded correctly (see [the docs](http://www.npgsql.org/efcore/mapping-and-translation.html)). -Here's the [full list of issues](https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL/milestone/6?closed=1). Please report any problems to https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL. +Here's the [full list of issues](https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL/milestone/6?closed=1). Please report any problems to . ## Upgrading from 1.x @@ -24,18 +24,18 @@ Thank you very much to the following people who have contributed to the individu ### [Milestone 2.0.2](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.0.2) -| Contributor | Assigned issues | -| ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| -| [@roji](https://github.com/roji) | [4](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.0.2+is%3Aclosed+assignee%3Aroji) | +Contributor | Assigned issues +-------------------------------- | ---------------:| +[@roji](https://github.com/roji) | [4](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.0.2+is%3Aclosed+assignee%3Aroji) ### [Milestone 2.0.1](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.0.1) -| Contributor | Assigned issues | -| ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| -| [@roji](https://github.com/roji) | [5](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.0.1+is%3Aclosed+assignee%3Aroji) | +Contributor | Assigned issues +-------------------------------- | ---------------:| +[@roji](https://github.com/roji) |[5](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.0.1+is%3Aclosed+assignee%3Aroji) ### [Milestone 2.0.0](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.0.0) -| Contributor | Assigned issues | -| ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| -| [@roji](https://github.com/roji) | [16](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.0.0+is%3Aclosed+assignee%3Aroji) | +Contributor | Assigned issues +-------------------------------- | ---------------:| +[@roji](https://github.com/roji) | [16](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.0.0+is%3Aclosed+assignee%3Aroji) diff --git a/docs/release-notes/2.1.md b/docs/release-notes/2.1.md index a5d0baf134..031de9f09c 100644 --- a/docs/release-notes/2.1.md +++ b/docs/release-notes/2.1.md @@ -68,7 +68,7 @@ Many thanks to [@austindrenski](https://github.com/austindrenski) for contributi * Added support for PostgreSQL 10 sequences with type `int` and `smallint` ([#301](https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL/issues/301)). * You can now specify the [tablespace](https://www.postgresql.org/docs/current/static/manage-ag-tablespaces.html) when creating your databases ([#332](https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL/issues/332)). -Here's the [full list of issues](https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL/milestone/8?closed=1). Please report any problems on https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL. +Here's the [full list of issues](https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL/milestone/8?closed=1). Please report any problems on . ## Breaking changes @@ -80,40 +80,40 @@ Here's the [full list of issues](https://github.com/npgsql/Npgsql.EntityFramewor * Specifying versions when specifying PostgreSQL extensions on your model is no longer supported - this was a very rarely-used feature which interfered with extension scaffolding. * If you're still referencing the nuget package Npgsql.EntityFrameworkCore.PostgreSQL.Design, please remove it - it's no longer needed or up to date. -## Contributors: +## Contributors Thank you very much to the following people who have contributed to the individual 2.1.x. releases. ### [Milestone 2.1.2](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.1.2) -| Contributor | Assigned issues | -| ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| -| [@roji](https://github.com/roji) | [6](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.1.2+is%3Aclosed+assignee%3Aroji) | -| [@austindrenski](https://github.com/austindrenski) | [3](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.1.2+is%3Aclosed+assignee%3Aaustindrenski) | -| [@rwasef1830](https://github.com/rwasef1830) | [1](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.1.2+is%3Aclosed+assignee%3Arwasef1830) | +Contributor | Assigned issues +---------------------------------------------------- | ----------------:| +[@roji](https://github.com/roji) | [6](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.1.2+is%3Aclosed+assignee%3Aroji) +[@austindrenski](https://github.com/austindrenski) | [3](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.1.2+is%3Aclosed+assignee%3Aaustindrenski) +[@rwasef1830](https://github.com/rwasef1830) | [1](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.1.2+is%3Aclosed+assignee%3Arwasef1830) ### [Milestone 2.1.11](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.1.11) -| Contributor | Assigned issues | -| ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| -| [@roji](https://github.com/roji) | [1](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.1.11+is%3Aclosed+assignee%3Aroji) | +Contributor | Assigned issues +---------------------------------------------------- | ----------------:| +[@roji](https://github.com/roji) | [1](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.1.11+is%3Aclosed+assignee%3Aroji) ### [Milestone 2.1.1.1](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.1.1.1) -| Contributor | Assigned issues | -| ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| -| [@roji](https://github.com/roji) | [4](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.1.1.1+is%3Aclosed+assignee%3Aroji) | +Contributor | Assigned issues +---------------------------------------------------- | ----------------:| +[@roji](https://github.com/roji) | [4](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.1.1.1+is%3Aclosed+assignee%3Aroji) ### [Milestone 2.1.1](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.1.1) -| Contributor | Assigned issues | -| ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| -| [@roji](https://github.com/roji) | [9](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.1.1+is%3Aclosed+assignee%3Aroji) | +Contributor | Assigned issues +---------------------------------------------------- | ----------------:| +[@roji](https://github.com/roji) | [9](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.1.1+is%3Aclosed+assignee%3Aroji) ### [Milestone 2.1.0](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.1.0) -| Contributor | Assigned issues | -| ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| -| [@roji](https://github.com/roji) | [24](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.1.0+is%3Aclosed+assignee%3Aroji) | -| [@austindrenski](https://github.com/austindrenski) | [1](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.1.0+is%3Aclosed+assignee%3Aaustindrenski) | -| [@rwasef1830](https://github.com/rwasef1830) | [1](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.1.0+is%3Aclosed+assignee%3Arwasef1830) | +| Contributor | Assigned issues +| -------------------------------------------------- | ----------------:| +| [@roji](https://github.com/roji) | [24](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.1.0+is%3Aclosed+assignee%3Aroji) +| [@austindrenski](https://github.com/austindrenski) | [1](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.1.0+is%3Aclosed+assignee%3Aaustindrenski) +| [@rwasef1830](https://github.com/rwasef1830) | [1](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.1.0+is%3Aclosed+assignee%3Arwasef1830) diff --git a/docs/release-notes/2.2.md b/docs/release-notes/2.2.md index 9fcd16fbe0..770f09c37f 100644 --- a/docs/release-notes/2.2.md +++ b/docs/release-notes/2.2.md @@ -62,20 +62,20 @@ Thank you very much to the following people who have contributed to the individu ### [Milestone 2.2.6](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.2.6) -| Contributor | Assigned issues | -| ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| -| [@roji](https://github.com/roji) | [5](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.2.6+is%3Aclosed+assignee%3Aroji) | +Contributor | Assigned issues +------------------------------------------------ | ----------------:| +[@roji](https://github.com/roji) |[5](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.2.6+is%3Aclosed+assignee%3Aroji) ### [Milestone 2.2.4](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.2.4) -| Contributor | Assigned issues | -| ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| -| [@roji](https://github.com/roji) | [3](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.2.4+is%3Aclosed+assignee%3Aroji) | -| [@austindrenski](https://github.com/austindrenski) | [1](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.2.4+is%3Aclosed+assignee%3Aaustindrenski) | +Contributor | Assigned issues +-------------------------------------------------- | ----------------:| +[@roji](https://github.com/roji) | [3](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.2.4+is%3Aclosed+assignee%3Aroji) +[@austindrenski](https://github.com/austindrenski) | [1](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.2.4+is%3Aclosed+assignee%3Aaustindrenski) ### [Milestone 2.2.0](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.2.0) -| Contributor | Assigned issues | -| ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| -| [@austindrenski](https://github.com/austindrenski) | [15](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.2.0+is%3Aclosed+assignee%3Aaustindrenski) | -| [@roji](https://github.com/roji) | [8](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.2.0+is%3Aclosed+assignee%3Aroji) | +Contributor | Assigned issues +-------------------------------------------------- | ----------------:| +[@austindrenski](https://github.com/austindrenski) | [15](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.2.0+is%3Aclosed+assignee%3Aaustindrenski) +[@roji](https://github.com/roji) | [8](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.2.0+is%3Aclosed+assignee%3Aroji) diff --git a/docs/release-notes/3.x.md b/docs/release-notes/3.x.md index 7daf31eb30..11f9648ca5 100644 --- a/docs/release-notes/3.x.md +++ b/docs/release-notes/3.x.md @@ -54,66 +54,66 @@ Thank you very much to the following people who have contributed to the individu ### [Milestone 3.1.7](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.1.7) -| Contributor | Assigned issues | -| ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| -| [@roji](https://github.com/roji) | [4](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.1.7+is%3Aclosed+assignee%3Aroji) | +Contributor | Assigned issues +-------------------------------------------------- | ----------------:| +[@roji](https://github.com/roji) | [4](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.1.7+is%3Aclosed+assignee%3Aroji) ### [Milestone 3.1.4](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.1.4) -| Contributor | Assigned issues | -| ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| -| [@roji](https://github.com/roji) | [4](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.1.4+is%3Aclosed+assignee%3Aroji) | +Contributor | Assigned issues +-------------------------------------------------- |-----------------:| +[@roji](https://github.com/roji) | [4](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.1.4+is%3Aclosed+assignee%3Aroji) ### [Milestone 3.1.3](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.1.3) -| Contributor | Assigned issues | -| ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| -| [@roji](https://github.com/roji) | [1](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.1.3+is%3Aclosed+assignee%3Aroji) | +Contributor | Assigned issues +-------------------------------------------------- |-----------------:| +[@roji](https://github.com/roji) | [1](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.1.3+is%3Aclosed+assignee%3Aroji) ### [Milestone 3.1.2](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.1.2) -| Contributor | Assigned issues | -| ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| -| [@roji](https://github.com/roji) | [3](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.1.2+is%3Aclosed+assignee%3Aroji) | -| [@grzybsonssg](https://github.com/grzybsonssg) | [1](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.1.2+is%3Aclosed+assignee%3Agrzybsonssg) | +Contributor | Assigned issues +-------------------------------------------------- | ----------------:| +[@roji](https://github.com/roji) | [3](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.1.2+is%3Aclosed+assignee%3Aroji) +[@grzybsonssg](https://github.com/grzybsonssg) | [1](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.1.2+is%3Aclosed+assignee%3Agrzybsonssg) ### [Milestone 3.1.1.2](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.1.1.2) -| Contributor | Assigned issues | -| ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| -| [@roji](https://github.com/roji) | [1](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.1.1.2+is%3Aclosed+assignee%3Aroji) | +Contributor | Assigned issues +-------------------------------------------------- | ----------------:| +[@roji](https://github.com/roji) | [1](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.1.1.2+is%3Aclosed+assignee%3Aroji) ### [Milestone 3.1.1.1](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.1.1.1) -| Contributor | Assigned issues | -| ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| -| [@roji](https://github.com/roji) | [1](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.1.1.1+is%3Aclosed+assignee%3Aroji) | +Contributor | Assigned issues +-------------------------------------------------- | ----------------:| +[@roji](https://github.com/roji) | [1](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.1.1.1+is%3Aclosed+assignee%3Aroji) ### [Milestone 3.1.1](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.1.1) -| Contributor | Assigned issues | -| ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| -| [@roji](https://github.com/roji) | [6](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.1.1+is%3Aclosed+assignee%3Aroji) | +Contributor | Assigned issues +-------------------------------------------------- | ----------------:| +[@roji](https://github.com/roji) | [6](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.1.1+is%3Aclosed+assignee%3Aroji) ### [Milestone 3.1.0](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.1.0) -| Contributor | Assigned issues | -| ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| -| [@roji](https://github.com/roji) | [15](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.1.0+is%3Aclosed+assignee%3Aroji) | -| [@austindrenski](https://github.com/austindrenski) | [1](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.1.0+is%3Aclosed+assignee%3Aaustindrenski) | -| [@ins0mniaque](https://github.com/ins0mniaque) | [1](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.1.0+is%3Aclosed+assignee%3Ains0mniaque) | -| [@MarioPrabowo](https://github.com/MarioPrabowo) | [1](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.1.0+is%3Aclosed+assignee%3AMarioPrabowo) | +Contributor | Assigned issues +-------------------------------------------------- | ----------------:| +[@roji](https://github.com/roji) | [15](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.1.0+is%3Aclosed+assignee%3Aroji) +[@austindrenski](https://github.com/austindrenski) | [1](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.1.0+is%3Aclosed+assignee%3Aaustindrenski) +[@ins0mniaque](https://github.com/ins0mniaque) | [1](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.1.0+is%3Aclosed+assignee%3Ains0mniaque) +[@MarioPrabowo](https://github.com/MarioPrabowo) | [1](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.1.0+is%3Aclosed+assignee%3AMarioPrabowo) ### [Milestone 3.0.1](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.0.1) -| Contributor | Assigned issues | -| ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| -| [@roji](https://github.com/roji) | [1](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.0.1+is%3Aclosed+assignee%3Aroji) | +Contributor | Assigned issues +-------------------------------------------------- | ----------------:| +[@roji](https://github.com/roji) | [1](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.0.1+is%3Aclosed+assignee%3Aroji) ### [Milestone 3.0.0](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.0.0) -| Contributor | Assigned issues | -| ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| -| [@roji](https://github.com/roji) | [25](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.0.0+is%3Aclosed+assignee%3Aroji) | -| [@austindrenski](https://github.com/austindrenski) | [2](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.0.0+is%3Aclosed+assignee%3Aaustindrenski) | -| [@YohDeadfall](https://github.com/YohDeadfall) | [1](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.0.0+is%3Aclosed+assignee%3AYohDeadfall) | +Contributor | Assigned issues +-------------------------------------------------- | ----------------:| +[@roji](https://github.com/roji) | [25](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.0.0+is%3Aclosed+assignee%3Aroji) +[@austindrenski](https://github.com/austindrenski) | [2](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.0.0+is%3Aclosed+assignee%3Aaustindrenski) +[@YohDeadfall](https://github.com/YohDeadfall) | [1](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.0.0+is%3Aclosed+assignee%3AYohDeadfall) diff --git a/docs/toc.md b/docs/toc.md deleted file mode 100644 index a742d01f75..0000000000 --- a/docs/toc.md +++ /dev/null @@ -1,27 +0,0 @@ -# [Getting Started](index.md) -# Release Notes -## [3.x](release-notes/3.x.md) -## [2.2](release-notes/2.2.md) -## [2.1](release-notes/2.1.md) -## [2.0](release-notes/2.0.md) -## [1.1](release-notes/1.1.md) -# Creating a Model -## [Table and Column Naming](modeling/table-column-naming.md) -## [Generated Properties](modeling/generated-properties.md) -## [Concurrency Tokens](modeling/concurrency.md) -## [Indexes](modeling/indexes.md) -# Mapping and Translation -## [General](mapping/general.md) -## [Translations](mapping/translations.md) -## [JSON](mapping/json.md) -## [Spatial Data](mapping/nts.md) -## [Full Text Search](mapping/full-text-search.md) -## [NodaTime](mapping/nodatime.md) -## [Arrays](mapping/array.md) -## [Enums](mapping/enum.md) -## [Ranges](mapping/range.md) -# Miscellaneous -## [Collations and Case Sensitivity](misc/collations-and-case-sensitivity.md) -## [Database Creation](misc/database-creation.md) -## [Other](misc/other.md) -# [API Reference](../../obj/api/EFCore.PG/) diff --git a/docs/toc.yml b/docs/toc.yml new file mode 100644 index 0000000000..4f8a1b425a --- /dev/null +++ b/docs/toc.yml @@ -0,0 +1,54 @@ +- name: Getting started + href: index.md +- name: Release notes + items: + - name: "3.x" + href: release-notes/3.x.md + - name: "2.2" + href: release-notes/2.2.md + - name: "2.1" + href: release-notes/2.1.md + - name: "2.0" + href: release-notes/2.0.md + - name: "1.1" + href: release-notes/1.1.md +- name: Creating a model + items: + - name: Table and column naming + href: modeling/table-column-naming.md + - name: Generated properties + href: modeling/generated-properties.md + - name: Concurrency tokens + href: modeling/concurrency.md + - name: Indexes + href: modeling/indexes.md +- name: Mapping and translation + items: + - name: General + href: mapping/general.md + - name: Translations + href: mapping/translations.md + - name: JSON + href: mapping/json.md + - name: Spatial data + href: mapping/nts.md + - name: Full text search + href: mapping/full-text-search.md + - name: NodaTime + href: mapping/nodatime.md + - name: Arrays + href: mapping/array.md + - name: Enums + href: mapping/enum.md + - name: Ranges + href: mapping/range.md +- name: Miscellaneous + items: + - name: Collations and case sensitivity + href: misc/collations-and-case-sensitivity.md + - name: Database creation + href: misc/database-creation.md + - name: Other + href: misc/other.md +- name: API reference + href: "../../obj/api/EFCore.PG/" From cc75b3f7442dbbbf7789798f84355d33217b9e11 Mon Sep 17 00:00:00 2001 From: Jeremy Cook Date: Mon, 19 Oct 2020 17:17:34 -0600 Subject: [PATCH 039/207] Fix implicit and hidden system columns link in concurrency.md --- docs/modeling/concurrency.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/modeling/concurrency.md b/docs/modeling/concurrency.md index 57b13cabfc..ebad26aea2 100644 --- a/docs/modeling/concurrency.md +++ b/docs/modeling/concurrency.md @@ -7,7 +7,7 @@ Entity Framework Core supports the concept of optimistic concurrency - a propert ## The PostgreSQL xmin system column -Although applications can update concurrency tokens themselves, we frequently rely on the database automatically updating a column on update - a "last modified" timestamp, an SQL Server `rowversion`, etc. Unfortunately PostgreSQL doesn't have such auto-updating columns - but there is one feature that can be used for concurrency token. All PostgreSQL tables have a set of [implicit and hidden system columns](https://www.postgresql.org/docs/current/static/ddl-system-columns.htm://www.postgresql.org/docs/current/static/ddl-system-columns.html), among which `xmin` holds the ID of the latest updating transaction. Since this value automatically gets updated every time the row is changed, it is ideal for use as a concurrency token. +Although applications can update concurrency tokens themselves, we frequently rely on the database automatically updating a column on update - a "last modified" timestamp, an SQL Server `rowversion`, etc. Unfortunately PostgreSQL doesn't have such auto-updating columns - but there is one feature that can be used for concurrency token. All PostgreSQL tables have a set of [implicit and hidden system columns](https://www.postgresql.org/docs/current/ddl-system-columns.html), among which `xmin` holds the ID of the latest updating transaction. Since this value automatically gets updated every time the row is changed, it is ideal for use as a concurrency token. To enable this feature on an entity, insert the following code into your context's `OnModelCreating` method: From b3a16733aed4ea1a73d0b2e33be84b3c387c2b96 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Tue, 20 Oct 2020 15:03:37 +0300 Subject: [PATCH 040/207] Some minor fixes --- docs/mapping/full-text-search.md | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/docs/mapping/full-text-search.md b/docs/mapping/full-text-search.md index 39e4923fef..3da1d22c2f 100644 --- a/docs/mapping/full-text-search.md +++ b/docs/mapping/full-text-search.md @@ -34,7 +34,7 @@ public class Product } ``` -Setting up the column to be auto-updated depends on your PostgreSQL version. On PostgreSQL 12 and above, the column can be a simple [generated column](../modeling/generated-properties#computed-columns-on-add-or-update), and version 5.0.0 contains sugar for setting that up. In previous versions, you must manually set up database triggers that update the column instead. +Setting up the column to be auto-updated depends on your PostgreSQL version. On PostgreSQL 12 and above, the column can be a simple [generated column](../modeling/generated-properties.md#computed-columns-on-add-or-update), and version 5.0.0 contains sugar for setting that up. In previous versions, you must manually set up database triggers that update the column instead. #### [PostgreSQL 12+](#tab/pg12) @@ -55,7 +55,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) .HasMethod("GIN"); // Index method on the search vector (GIN or GIST) ``` -#### [Older Versions](#tab/pgold) +#### [Older Versions](#tab/older) First, modify the `OnModelCreating()` of your context class to add an index as follows: @@ -68,6 +68,8 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) } ``` +*** + Now generate a migration (`dotnet ef migrations add ....`), and open it with your favorite editor, adding the following: ```c# @@ -109,7 +111,7 @@ var npgsql = context.Products Version 5.0.0 of the provider includes sugar for defining the appropriate expression index; if you're using an older version, you'll have to define a raw SQL migration yourself. -#### [EF Core 5+](#tab/pg12) +#### [PostgreSQL 12+](#tab/pg12) ```c# modelBuilder.Entity() @@ -117,7 +119,7 @@ modelBuilder.Entity() .IsTsVectorExpressionIndex("english"); ``` -#### [Older Versions](#tab/efold) +#### [Older Versions](#tab/older) Create a migration which will contain the index creation SQL (`dotnet ef migrations add ...`). At this point, open the generated migration with your editor and add the following: From 9071d5a7ee1e0746e7f056f1e4dea89d80e93a75 Mon Sep 17 00:00:00 2001 From: oshawa-connection <36929345+oshawa-connection@users.noreply.github.com> Date: Sun, 25 Oct 2020 05:43:49 +0000 Subject: [PATCH 041/207] Adding more supported spatial operations (#67) --- docs/mapping/nts.md | 28 +++++++++++++++++++++++++--- 1 file changed, 25 insertions(+), 3 deletions(-) diff --git a/docs/mapping/nts.md b/docs/mapping/nts.md index eeb27997f4..ca3025ec9c 100644 --- a/docs/mapping/nts.md +++ b/docs/mapping/nts.md @@ -88,37 +88,59 @@ Note that the plugin is far from covering all spatial operations. If an operatio .NET | SQL ---------------------------------|----- geom.Area() | [ST_Area(geom)](https://postgis.net/docs/manual-3.0/ST_Area.html) +geom.AsBinary() | [ST_AsBinary(geom)](https://postgis.net/docs/manual-3.0/ST_AsBinary.html) geom.AsText() | [ST_AsText(geom)](https://postgis.net/docs/manual-3.0/ST_AsText.html) geom.Boundary | [ST_Boundary(geom)](https://postgis.net/docs/manual-3.0/ST_Boundary.html) +geom.Buffer(d) | [ST_Buffer(geom,d)](https://postgis.net/docs/manual-3.0/ST_Buffer.html) +geom.Centroid | [ST_Centroid(geom)](https://postgis.net/docs/manual-3.0/ST_Centroid.html) geom1.Contains(geom2)) | [ST_Contains(geom1, geom2)](https://postgis.net/docs/manual-3.0/ST_Contains.html) +geomCollection.Count | [ST_NumGeometries(geom1)](https://postgis.net/docs/manual-3.0/ST_NumGeometries.html) +linestring.Count | [ST_NumPoints(linestring)](https://postgis.net/docs/manual-3.0/ST_NumPoints.html) +geom1.ConvexHull() | [ST_ConvexHull(geom1)](https://postgis.net/docs/manual-3.0/ST_ConvexHull.html) geom1.Covers(geom2)) | [ST_Covers(geom1, geom2)](https://postgis.net/docs/manual-3.0/ST_Covers.html) geom1.CoveredBy(geom2)) | [ST_CoveredBy(geom1, geom2)](https://postgis.net/docs/manual-3.0/ST_CoveredBy.html) geom1.Crosses(geom2) | [ST_Crosses(geom1, geom2)](https://postgis.net/docs/manual-3.0/ST_Crosses.html) geom1.Difference(geom2) | [ST_Difference(geom1, geom2)](https://postgis.net/docs/manual-3.0/ST_Difference.html) +geom1.Dimension | [ST_Dimension(geom1)](https://postgis.net/docs/manual-3.0/ST_Dimension.html) geom1.Disjoint(geom2)) | [ST_Disjoint(geom1, geom2)](https://postgis.net/docs/manual-3.0/ST_Disjoint.html) geom1.Distance(geom2) | [ST_Distance(geom1, geom2)](https://postgis.net/docs/manual-3.0/ST_Distance.html) +geom1.Envelope | [ST_Envelope(geom1)](https://postgis.net/docs/manual-3.0/ST_Envelope.html) +geom1.ExactEquals(geom2) | [ST_OrderingEquals(geom1, geom2)](https://postgis.net/docs/manual-3.0/ST_OrderingEquals.html) +lineString.EndPoint | [ST_EndPoint(lineString)](https://postgis.net/docs/manual-3.0/ST_EndPoint.html) +polygon.ExteriorRing | [ST_ExteriorRing(polygon)](https://postgis.net/docs/manual-3.0/ST_ExteriorRing.html) geom1.Equals(geom2) | [geom1 = geom2](https://postgis.net/docs/manual-3.0/ST_Geometry_EQ.html) geom1.Polygon.EqualsExact(geom2) | [geom1 = geom2](https://postgis.net/docs/manual-3.0/ST_Geometry_EQ.html) geom1.EqualsTopologically(geom2) | [ST_Equals(geom1, geom2)](https://postgis.net/docs/manual-3.0/ST_Equals.html) -geom.GeometryType() | [GeometryType(geom)](https://postgis.net/docs/manual-3.0/GeometryType.html) +geom.GeometryType | [GeometryType(geom)](https://postgis.net/docs/manual-3.0/GeometryType.html) geomCollection.GetGeometryN(i) | [ST_GeometryN(geomCollection, i)](https://postgis.net/docs/manual-3.0/ST_GeometryN.html) +linestring.GetPointN(i) | [ST_PointN(linestring, i)](https://postgis.net/docs/manual-3.0/ST_PointN.html) geom1.Intersection(geom2) | [ST_Intersection(geom1, geom2)](https://postgis.net/docs/manual-3.0/ST_Intersection.html) -geom2.Intersects(geom2) | [ST_Intersects(geom1, geom2)](https://postgis.net/docs/manual-3.0/ST_Intersects.html) +geom1.Intersects(geom2) | [ST_Intersects(geom1, geom2)](https://postgis.net/docs/manual-3.0/ST_Intersects.html) +geom.InteriorPoint | [ST_PointOnSurface(geom)](https://postgis.net/docs/manual-3.0/ST_PointOnSurface.html) lineString.IsClosed() | [ST_IsClosed(lineString)](https://postgis.net/docs/manual-3.0/ST_IsClosed.html) geomCollection.IsEmpty() | [ST_IsEmpty(geomCollection)](https://postgis.net/docs/manual-3.0/ST_IsEmpty.html) +linestring.IsRing | [ST_IsRing(linestring)](https://postgis.net/docs/manual-3.0/ST_IsRing.html) +geom.IsWithinDistance(geom2,d) | [ST_DWithin(geom1,geom2,d)](https://postgis.net/docs/manual-3.0/ST_DWithin.html) geom.IsSimple() | [ST_IsSimple(geom)](https://postgis.net/docs/manual-3.0/ST_IsSimple.html) geom.IsValid() | [ST_IsValid(geom)](https://postgis.net/docs/manual-3.0/ST_IsValid.html) lineString.Length | [ST_Length(lineString)](https://postgis.net/docs/manual-3.0/ST_Length.html) +geom.Normalized | [ST_Normalize(geom)](https://postgis.net/docs/manual-3.0/ST_Normalize.html) geomCollection.NumGeometries | [ST_NumGeometries(geomCollection)](https://postgis.net/docs/manual-3.0/ST_NumGeometries.html) +polygon.NumInteriorRings | [ST_NumInteriorRings(polygon)](https://postgis.net/docs/manual-3.0/ST_NumInteriorRings.html) lineString.NumPoints | [ST_NumPoints(lineString)](https://postgis.net/docs/manual-3.0/ST_NumPoints.html) geom1.Overlaps(geom2)) | [ST_Overlaps(geom1, geom2)](https://postgis.net/docs/manual-3.0/ST_Overlaps.html) +geom.PointOnSurface | [ST_PointOnSurface(geom)](https://postgis.net/docs/manual-3.0/ST_PointOnSurface.html) geom1.Relate(geom2) | [ST_Relate(geom1, geom2)](https://postgis.net/docs/manual-3.0/ST_Relate.html) geom.Reverse() | [ST_Reverse(geom)](https://postgis.net/docs/manual-3.0/ST_Reverse.html) +geom1.SRID | [ST_SRID(geom1)](https://postgis.net/docs/manual-3.0/ST_SRID.html) +lineString.StartPoint | [ST_StartPoint(lineString)](https://postgis.net/docs/manual-3.0/ST_StartPoint.html) geom1.SymmetricDifference(geom2) | [ST_SymDifference(geom1, geom2)](https://postgis.net/docs/manual-3.0/ST_SymDifference.html) -geom1.Touches(geom2)) | [ST_Touches(geom1, geom2)](https://postgis.net/docs/manual-3.0/ST_Touches.html) +geom.ToBinary() | [ST_AsBinary(geom)](https://postgis.net/docs/manual-3.0/ST_AsBinary.html) geom.ToText() | [ST_AsText(geom)](https://postgis.net/docs/manual-3.0/ST_AsText.html) +geom1.Touches(geom2)) | [ST_Touches(geom1, geom2)](https://postgis.net/docs/manual-3.0/ST_Touches.html) geom1.Union(geom2) | [ST_Union(geom1, geom2)](https://postgis.net/docs/manual-3.0/ST_Union.html) geom1.Within(geom2) | [ST_Within(geom1, geom2)](https://postgis.net/docs/manual-3.0/ST_Within.html) +point.M | [ST_M(point)](https://postgis.net/docs/manual-3.0/ST_M.html) point.X | [ST_X(point)](https://postgis.net/docs/manual-3.0/ST_X.html) point.Y | [ST_Y(point)](https://postgis.net/docs/manual-3.0/ST_Y.html) point.Z | [ST_Z(point)](https://postgis.net/docs/manual-3.0/ST_Z.html) From 44279d651075ce29fc517eb331cfdfad1f603739 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Mon, 26 Oct 2020 10:20:39 +0200 Subject: [PATCH 042/207] Release notes for the EFCore.PG 5.0 release Plus add docs for: * Computed columns in 5.0 * IsCreatedConcurrently * [JsonPropertyName] --- docs/mapping/json.md | 5 ++- docs/modeling/generated-properties.md | 19 ++++++++- docs/modeling/indexes.md | 19 +++++++++ docs/release-notes/5.0.md | 60 +++++++++++++++++++++++++++ docs/toc.yml | 2 + 5 files changed, 101 insertions(+), 4 deletions(-) create mode 100644 docs/release-notes/5.0.md diff --git a/docs/mapping/json.md b/docs/mapping/json.md index f4f11802e8..289961509e 100644 --- a/docs/mapping/json.md +++ b/docs/mapping/json.md @@ -112,6 +112,7 @@ public class Customer // Mapped to a JSON column in the table public class Order // Part of the JSON column { + [JsonPropertyName("OrderPrice")] // Controls the JSON property name public decimal Price { get; set; } public string ShippingAddress { get; set; } } @@ -126,8 +127,8 @@ You can now assign a regular `Customer` instance to the property, and once you c "Age": 25, "Name": "Joe", "Orders": [ - {"Price": 9, "ShippingAddress": "Some address 1"}, - {"Price": 23, "ShippingAddress": "Some address 2"} + { "OrderPrice": 9, "ShippingAddress": "Some address 1" }, + { "OrderPrice": 23, "ShippingAddress": "Some address 2" } ] } ``` diff --git a/docs/modeling/generated-properties.md b/docs/modeling/generated-properties.md index 362d0dc64a..aedcf26f89 100644 --- a/docs/modeling/generated-properties.md +++ b/docs/modeling/generated-properties.md @@ -116,12 +116,25 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) See [the PostgreSQL docs on UUID for more details](https://www.postgresql.org/docs/current/static/datatype-uuid.html). -## Computed Columns (On Add or Update) +## Computed Columns > [!NOTE] > This feature works only on PostgreSQL 12 or above, and was introduced in version 3.0.0 of the provider. -PostgreSQL 12 added support for [stored generated columns](https://www.postgresql.org/docs/12/ddl-generated-columns.html), and Npgsql feature supports that feature as well. The following configuration: +PostgreSQL 12 added support for [stored generated columns](https://www.postgresql.org/docs/current/ddl-generated-columns.html), and Npgsql feature supports that feature as well. The following configuration: + +### [Version 5.0](#tab/efcore5.0) + +```c# +protected override void OnModelCreating(ModelBuilder modelBuilder) +{ + modelBuilder.Entity() + .Property(p => p.DisplayName) + .HasComputedColumnSql(@"""FirstName"" || ' ' || ""LastName""", stored: true); +} +``` + +### [Version 3.x](#tab/efcore3.x) ```c# protected override void OnModelCreating(ModelBuilder modelBuilder) @@ -132,6 +145,8 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) } ``` +*** + Will cause the following migration SQL to be generated ```sql diff --git a/docs/modeling/indexes.md b/docs/modeling/indexes.md index a8a971715c..344b4d4eb6 100644 --- a/docs/modeling/indexes.md +++ b/docs/modeling/indexes.md @@ -48,3 +48,22 @@ Note that each operator class is used for the corresponding index column, by ord ```sql CREATE INDEX "IX_blogs_Id_Name" ON blogs ("Id", "Name" text_pattern_ops); ``` + +## Creating indexes concurrently + +Creating an index can interfere with regular operation of a database. Normally PostgreSQL locks the table to be indexed against writes and performs the entire index build with a single scan of the table. Other transactions can still read the table, but if they try to insert, update, or delete rows in the table they will block until the index build is finished. This could have a severe effect if the system is a live production database. Very large tables can take many hours to be indexed, and even for smaller tables, an index build can lock out writers for periods that are unacceptably long for a production system. + +The EF provider allows you to specify that an index should be created *concurrently*, partially mitigating the above issues: + +```c# +protected override void OnModelCreating(ModelBuilder modelBuilder) + => modelBuilder.Entity() + .HasIndex(b => b.Url) + .IsCreatedConcurrently(); +``` + +> [!CAUTION] +> Do not enable this feature before reading the [PostgreSQL documentation](https://www.postgresql.org/docs/current/sql-createindex.html#SQL-CREATEINDEX-CONCURRENTLY) and understanding the full implications of concurrent index creation. + +> [!NOTE] +> Prior to version 5.0, `IsCreatedConcurrently` erroneously defaulted to `false` - explicitly pass `true` to configure the index for concurrent creation diff --git a/docs/release-notes/5.0.md b/docs/release-notes/5.0.md new file mode 100644 index 0000000000..d9cd180c45 --- /dev/null +++ b/docs/release-notes/5.0.md @@ -0,0 +1,60 @@ +# 5.0 (RC) Release Notes + +Release candidates of version 5.0 of the Npgsql Entity Framework Core provider are available on nuget.org. These versions work with the corresponding RC versions of [Entity Framework Core 5.0](https://docs.microsoft.com/ef/core/what-is-new/ef-core-5.0/whatsnew), and brings new Npgsql features in addition to the general EF Core changes. + +The full list of issues for this release is [available here](https://github.com/npgsql/efcore.pg/milestone/24?closed=1). + +## New Features + +Aside from general EF Core features new in 5.0, here is a non-exhaustive list of features added in the Npgsql EF Core provider: + +* Full support for PostgreSQL collations. [See the docs](http://www.npgsql.org/efcore/misc/collations-and-case-sensitivity.html?tabs=data-annotations) for more info. +* It is now much easier to create indexes for full-text search ([#1097](https://github.com/npgsql/efcore.pg/issues/1097), [#1253](https://github.com/npgsql/efcore.pg/issues/1253)). [See the docs](www.npgsql.org/efcore/mapping/full-text-search.html) for more info. +* Sequences are now automatically updated after seeding data to avoid duplicate values ([#367](https://github.com/npgsql/efcore.pg/issues/367)). +* [The `[JsonPropertyName]` attribute](https://docs.microsoft.com/dotnet/api/system.text.json.serialization.jsonpropertynameattribute) is now respected when mapping to JSON ([#1419](https://github.com/npgsql/efcore.pg/issues/1419)). +* Improved support for PostgreSQL arrays: + * Mapping `List` is now fully supported ([#395](https://github.com/npgsql/efcore.pg/issues/395)). + * Mapping arrays of nullable value types (e.g. `int?[]`) is now supported ([#1025](https://github.com/npgsql/efcore.pg/issues/1025)). +* Query translations: + * [Precise, exhaustive documentation](http://www.npgsql.org/efcore/mapping/translations.html) has been added on which functions can be used in LINQ queries. + * `Contains` over arrays now uses indexes in various scenarios, improving performance ([#1372](https://github.com/npgsql/efcore.pg/issues/1372)). + * Various members of [TimeSpan](https://docs.microsoft.com/dotnet/api/system.timespan?view=netcore-3.1) are now translated and can be used in queries ([#328](https://github.com/npgsql/efcore.pg/issues/328)). + * Support for [unaccent](https://www.postgresql.org/docs/current/unaccent.html) ([#1530](https://github.com/npgsql/efcore.pg/issues/1530)). Thanks @cloudlucky. + * Various translations over byte array properties have been added ([#1225](https://github.com/npgsql/efcore.pg/issues/1225), [#1226](https://github.com/npgsql/efcore.pg/issues/1226). +* Improved null semantics for PostgreSQL-specific operations results in tighter and more efficient SQL ([#1142](https://github.com/npgsql/efcore.pg/issues/1142)). +* It is now possible to add labels to existing enums (but not remove or modify existing ones). The provider will generate the appropriate migrations ([#1182](https://github.com/npgsql/efcore.pg/issues/1182)). + +## Breaking changes + +Please consult the EF Core 5.0 [breaking changes page](https://docs.microsoft.com/ef/core/what-is-new/ef-core-5.0/breaking-changes) as well - the below lists only changes specific to the Npgsql provider. + +### Computed columns must now explicitly be configured as stored ([#1336](https://github.com/npgsql/efcore.pg/issues/1336)) + +Version 3.1 of the provider added support for [PostgreSQL generated columns](https://www.postgresql.org/docs/current/ddl-generated-columns.html) ([#939](https://github.com/npgsql/efcore.pg/issues/939)), referred to as [computed columns in EF Core](https://docs.microsoft.com/ef/core/modeling/generated-properties?tabs=data-annotations#computed-columns). EF Core 5.0 adds support for specifying whether a computed column is *virtual* (computed when fetched), or *stored* (persisted on disk and computed when modified). Aligning with most databases, EF Core by default creates virtual computed columns, but these are currently unsupported by PostgreSQL. + +As a result, you must explicitly specify on all computed columns that they are stored: + +```c# +modelBuilder.Entity() + .Property(p => p.FullName) + .HasComputedColumnSql("...", stored: true); +``` + +### IsCreatedConcurrently defaults to true ([#1212](https://github.com/npgsql/efcore.pg/issues/1212)) + +Previously, when `IsCreatedConcurrently` was used to configure an index without parameters, the default was `false` - this has changed to `true`. Note that indexes are never configured for for concurrent creation unless `IsCreatedConcurrently` is specified. + +## Contributors + +A big thank you to all the following people who contributed to the 5.0 release! + +### [Milestone 5.0.0](https://github.com/npgsql/EFCore.PG/issues?q=milestone%3A5.0.0+) + +Contributor | Assigned issues +---------------------------------------------- | ----------------:| +[@artfulsage](https://github.com/artfulsage) | [1](https://github.com/npgsql/EFCore.PG/issues?q=milestone%3A5.0.0+assignee%3Aartfulsage+) +[@cloudlucky](https://github.com/cloudlucky) | [1](https://github.com/npgsql/EFCore.PG/issues?q=milestone%3A5.0.0+assignee%3Acloudlucky+) +[@plamen-i](https://github.com/plamen-i) | [1](https://github.com/npgsql/EFCore.PG/issues?q=milestone%3A5.0.0+assignee%3Aplamen-i) +[@Quogu](https://github.com/Quogu) | [1](https://github.com/npgsql/EFCore.PG/issues?q=milestone%3A5.0.0+assignee%3AQuogu+) +[@YohDeadfall](https://github.com/yohdeadfall) | [1](https://github.com/npgsql/EFCore.PG/issues?q=milestone%3A5.0.0+assignee%3Ayohdeadfall+) +[@roji](https://github.com/roji) | [45](https://github.com/npgsql/EFCore.PG/issues?q=milestone%3A5.0.0+assignee%3Aroji) diff --git a/docs/toc.yml b/docs/toc.yml index 4f8a1b425a..b3b71fa0dc 100644 --- a/docs/toc.yml +++ b/docs/toc.yml @@ -2,6 +2,8 @@ href: index.md - name: Release notes items: + - name: "5.0 (RC)" + href: release-notes/5.0.md - name: "3.x" href: release-notes/3.x.md - name: "2.2" From 98d8e22f74d264034c90f129ad6d11d0f45ee85d Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Mon, 26 Oct 2020 10:53:26 +0200 Subject: [PATCH 043/207] Correct mention --- docs/release-notes/5.0.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/release-notes/5.0.md b/docs/release-notes/5.0.md index d9cd180c45..fe0b88d105 100644 --- a/docs/release-notes/5.0.md +++ b/docs/release-notes/5.0.md @@ -19,7 +19,7 @@ Aside from general EF Core features new in 5.0, here is a non-exhaustive list of * [Precise, exhaustive documentation](http://www.npgsql.org/efcore/mapping/translations.html) has been added on which functions can be used in LINQ queries. * `Contains` over arrays now uses indexes in various scenarios, improving performance ([#1372](https://github.com/npgsql/efcore.pg/issues/1372)). * Various members of [TimeSpan](https://docs.microsoft.com/dotnet/api/system.timespan?view=netcore-3.1) are now translated and can be used in queries ([#328](https://github.com/npgsql/efcore.pg/issues/328)). - * Support for [unaccent](https://www.postgresql.org/docs/current/unaccent.html) ([#1530](https://github.com/npgsql/efcore.pg/issues/1530)). Thanks @cloudlucky. + * Support for [unaccent](https://www.postgresql.org/docs/current/unaccent.html) ([#1530](https://github.com/npgsql/efcore.pg/issues/1530)). Thanks [@cloudlucky](https://github.com/cloudlucky). * Various translations over byte array properties have been added ([#1225](https://github.com/npgsql/efcore.pg/issues/1225), [#1226](https://github.com/npgsql/efcore.pg/issues/1226). * Improved null semantics for PostgreSQL-specific operations results in tighter and more efficient SQL ([#1142](https://github.com/npgsql/efcore.pg/issues/1142)). * It is now possible to add labels to existing enums (but not remove or modify existing ones). The provider will generate the appropriate migrations ([#1182](https://github.com/npgsql/efcore.pg/issues/1182)). From 15c17fbb671071a8275b368b8d183dbb73c4d565 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Mon, 26 Oct 2020 16:27:26 +0200 Subject: [PATCH 044/207] Add "out of support" node under release notes --- docs/release-notes/{3.x.md => 3.1.md} | 8 ++++---- docs/toc.yml | 18 ++++++++++-------- 2 files changed, 14 insertions(+), 12 deletions(-) rename docs/release-notes/{3.x.md => 3.1.md} (97%) diff --git a/docs/release-notes/3.x.md b/docs/release-notes/3.1.md similarity index 97% rename from docs/release-notes/3.x.md rename to docs/release-notes/3.1.md index 11f9648ca5..b8f3e9e272 100644 --- a/docs/release-notes/3.x.md +++ b/docs/release-notes/3.1.md @@ -1,4 +1,4 @@ -# 3.x Release Notes +# 3.1 Release Notes Version 3.1 of the Npgsql Entity Framework Core provider has been released and is available on nuget. This version works with [version 3.1 of Entity Framework Core](https://docs.microsoft.com/ef/core/what-is-new/ef-core-3.x), and brings new Npgsql features in addition to the general EF Core changes. @@ -9,7 +9,7 @@ The full list of issues for this release is [available here](https://github.com/ ## New Features -Aside from general EF Core features new in 3.x, the Npgsql EF Core provider contains the following major new features: +Aside from general EF Core features new in 3.1, the Npgsql EF Core provider contains the following major new features: * It is now possible to map POCOs to JSON columns and query them, [see the docs for more info](../mapping/json.md) ([#981](https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL/issues/981)) * PostgreSQL identity columns are now the default - see breaking changes below) ([#804](https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL/issues/804)) @@ -26,11 +26,11 @@ Aside from general EF Core features new in 3.x, the Npgsql EF Core provider cont ### Default value generation strategy is now IDENTITY > [!CAUTION] -> This is a major change, and upgrading to 3.x with an existing database will cause a non-trivial schema migration to be generated. Read the following carefully. +> This is a major change, and upgrading to 3.1 with an existing database will cause a non-trivial schema migration to be generated. Read the following carefully. The default value generation strategy has changed from the older SERIAL columns to the newer IDENTITY columns, introduced in PostgreSQL 10. -When producing a migration with 3.x, the Npgsql provider will attempt to automatically generate SQL to alter your tables and convert serial columns to identity ones. This is a sensitive, one-time migration operation that should be done with care, and carefully tested before deployment to production. +When producing a migration with 3.1, the Npgsql provider will attempt to automatically generate SQL to alter your tables and convert serial columns to identity ones. This is a sensitive, one-time migration operation that should be done with care, and carefully tested before deployment to production. If you wish to opt out of using IDENTITY columns and continue using SERIAL columns, set the following on your model: diff --git a/docs/toc.yml b/docs/toc.yml index b3b71fa0dc..7c7c644e83 100644 --- a/docs/toc.yml +++ b/docs/toc.yml @@ -4,16 +4,18 @@ items: - name: "5.0 (RC)" href: release-notes/5.0.md - - name: "3.x" - href: release-notes/3.x.md - - name: "2.2" - href: release-notes/2.2.md + - name: "3.1" + href: release-notes/3.1.md - name: "2.1" href: release-notes/2.1.md - - name: "2.0" - href: release-notes/2.0.md - - name: "1.1" - href: release-notes/1.1.md + - name: Out of support + items: + - name: "2.2" + href: release-notes/2.2.md + - name: "2.0" + href: release-notes/2.0.md + - name: "1.1" + href: release-notes/1.1.md - name: Creating a model items: - name: Table and column naming From 1c87f42145cf8d163eaad17db2d22992816fcdc8 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Thu, 29 Oct 2020 01:02:13 +0200 Subject: [PATCH 045/207] Fix JsonDocument usage docs Fixes #58 --- docs/mapping/json.md | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/docs/mapping/json.md b/docs/mapping/json.md index 289961509e..93453d51f7 100644 --- a/docs/mapping/json.md +++ b/docs/mapping/json.md @@ -160,7 +160,7 @@ Once a document is loaded from the database, you can traverse it: ```c# var someEntity = context.Entities.First(); -Console.WriteLine(someEntity.Customer.GetProperty("Orders")[0].GetProperty("Price").GetInt32()); +Console.WriteLine(someEntity.Customer.RootElement.GetProperty("Orders")[0].GetProperty("Price").GetInt32()); ``` ## Querying JSON columns @@ -179,7 +179,7 @@ var joes = context.CustomerEntries ```c# var joes = context.CustomerEntries - .Where(e => e.Customer.GetProperty("Name").GetString() == "Joe") + .Where(e => e.Customer.RootElement.GetProperty("Name").GetString() == "Joe") .ToList(); ``` @@ -213,17 +213,17 @@ EF.Functions.JsonTypeof(e.Customer.Age) | [j ### [JsonDocument Mapping](#tab/jsondocument) -.NET | SQL -----------------------------------------------------------------------------|----- -customer.GetProperty("Name").GetString() | [customer->>'Name' = 'Joe'](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-OP-TABLE) -customer.GetProperty("Orders")[1].GetProperty("Price").GetInt32() | [customer#>>'{Orders,0,Price}'[1] = 8](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-OP-TABLE) -customer.GetProperty("Orders").GetArrayLength() | [jsonb_array_length(customer->'Orders'](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-PROCESSING-TABLE) -EF.Functions.JsonContains(customer, @"{""Name"": ""Joe"", ""Age"": 25}") | [customer @> '{"Name": "Joe", "Age": 25}'](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) -EF.Functions.JsonContained(@"{""Name"": ""Joe"", ""Age"": 25}", customer) | ['{"Name": "Joe", "Age": 25}' <@ customer](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) -EF.Functions.JsonExists(customer, "Age") | [customer ? 'Age'](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) -EF.Functions.JsonExistsAny(customer, "Age", "Address") | [customer ?\| ARRAY['Age','Address']](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) -EF.Functions.JsonExistsAll(customer, "Age", "Address") | [customer ?& ARRAY['Age','Address']](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) -EF.Functions.JsonTypeof(customer.GetProperty("Age") == "number") | [jsonb_typeof(customer->'Age') = 'number'](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-PROCESSING-TABLE) +.NET | SQL +------------------------------------------------------------------------------|----- +customer.RootElement.GetProperty("Name").GetString() | [customer->>'Name' = 'Joe'](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-OP-TABLE) +customer.RootElement.GetProperty("Orders")[1].GetProperty("Price").GetInt32() | [customer#>>'{Orders,0,Price}'[1] = 8](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-OP-TABLE) +customer.RootElement.GetProperty("Orders").GetArrayLength() | [jsonb_array_length(customer->'Orders'](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-PROCESSING-TABLE) +EF.Functions.JsonContains(customer, @"{""Name"": ""Joe"", ""Age"": 25}") | [customer @> '{"Name": "Joe", "Age": 25}'](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) +EF.Functions.JsonContained(@"{""Name"": ""Joe"", ""Age"": 25}", customer) | ['{"Name": "Joe", "Age": 25}' <@ customer](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) +EF.Functions.JsonExists(customer, "Age") | [customer ? 'Age'](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) +EF.Functions.JsonExistsAny(customer, "Age", "Address") | [customer ?\| ARRAY['Age','Address']](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) +EF.Functions.JsonExistsAll(customer, "Age", "Address") | [customer ?& ARRAY['Age','Address']](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) +EF.Functions.JsonTypeof(customer.GetProperty("Age") == "number") | [jsonb_typeof(customer->'Age') = 'number'](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-PROCESSING-TABLE) *** From 2ceeeb9ea26c773f6ee816f07efce8c0c8edde91 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Tue, 10 Nov 2020 00:37:09 +0200 Subject: [PATCH 046/207] Add NodaTime improvements to EFCore.PG 5.0 release notes --- docs/release-notes/5.0.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/docs/release-notes/5.0.md b/docs/release-notes/5.0.md index fe0b88d105..40c0b691cc 100644 --- a/docs/release-notes/5.0.md +++ b/docs/release-notes/5.0.md @@ -22,6 +22,9 @@ Aside from general EF Core features new in 5.0, here is a non-exhaustive list of * Support for [unaccent](https://www.postgresql.org/docs/current/unaccent.html) ([#1530](https://github.com/npgsql/efcore.pg/issues/1530)). Thanks [@cloudlucky](https://github.com/cloudlucky). * Various translations over byte array properties have been added ([#1225](https://github.com/npgsql/efcore.pg/issues/1225), [#1226](https://github.com/npgsql/efcore.pg/issues/1226). * Improved null semantics for PostgreSQL-specific operations results in tighter and more efficient SQL ([#1142](https://github.com/npgsql/efcore.pg/issues/1142)). +* Better support for NodaTime: + * It is now possible to map NodaTime `Duration` to PostgreSQL `interval`, previously only `Period` could be mapped ([#1567](https://github.com/npgsql/efcore.pg/issues/1567). + * Some additional arithmetic operation are now translated ([#1565](https://github.com/npgsql/efcore.pg/issues/1565)). * It is now possible to add labels to existing enums (but not remove or modify existing ones). The provider will generate the appropriate migrations ([#1182](https://github.com/npgsql/efcore.pg/issues/1182)). ## Breaking changes From 6e0f43df166ed08ebda1010b9886474bc3205e63 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Sun, 15 Nov 2020 22:44:50 +0200 Subject: [PATCH 047/207] Update release notes for the 5.0 release --- docs/release-notes/5.0.md | 8 ++++---- docs/toc.yml | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/docs/release-notes/5.0.md b/docs/release-notes/5.0.md index 40c0b691cc..528b6ad02b 100644 --- a/docs/release-notes/5.0.md +++ b/docs/release-notes/5.0.md @@ -1,8 +1,6 @@ -# 5.0 (RC) Release Notes +# 5.0 Release Notes -Release candidates of version 5.0 of the Npgsql Entity Framework Core provider are available on nuget.org. These versions work with the corresponding RC versions of [Entity Framework Core 5.0](https://docs.microsoft.com/ef/core/what-is-new/ef-core-5.0/whatsnew), and brings new Npgsql features in addition to the general EF Core changes. - -The full list of issues for this release is [available here](https://github.com/npgsql/efcore.pg/milestone/24?closed=1). +Version 5.0 of the Npgsql Entity Framework Core provider has been released and is available on nuget. This version works with [version 5.0 of Entity Framework Core](https://docs.microsoft.com/ef/core/what-is-new/ef-core-5.0/whatsnew), and brings new Npgsql features in addition to the general EF Core changes. ## New Features @@ -27,6 +25,8 @@ Aside from general EF Core features new in 5.0, here is a non-exhaustive list of * Some additional arithmetic operation are now translated ([#1565](https://github.com/npgsql/efcore.pg/issues/1565)). * It is now possible to add labels to existing enums (but not remove or modify existing ones). The provider will generate the appropriate migrations ([#1182](https://github.com/npgsql/efcore.pg/issues/1182)). +The full list of issues for this release is [available here](https://github.com/npgsql/efcore.pg/milestone/24?closed=1). + ## Breaking changes Please consult the EF Core 5.0 [breaking changes page](https://docs.microsoft.com/ef/core/what-is-new/ef-core-5.0/breaking-changes) as well - the below lists only changes specific to the Npgsql provider. diff --git a/docs/toc.yml b/docs/toc.yml index 7c7c644e83..29000e665b 100644 --- a/docs/toc.yml +++ b/docs/toc.yml @@ -2,7 +2,7 @@ href: index.md - name: Release notes items: - - name: "5.0 (RC)" + - name: "5.0" href: release-notes/5.0.md - name: "3.1" href: release-notes/3.1.md From 2141f0a4f44e26d0c736e3aa0e3bb2984039313a Mon Sep 17 00:00:00 2001 From: Nirvin M Date: Mon, 30 Nov 2020 10:00:30 +0530 Subject: [PATCH 048/207] Postgres 12+ does not require trigger setup to update generated search vector column --- docs/mapping/full-text-search.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/docs/mapping/full-text-search.md b/docs/mapping/full-text-search.md index 3da1d22c2f..fc84ca1eb7 100644 --- a/docs/mapping/full-text-search.md +++ b/docs/mapping/full-text-search.md @@ -68,8 +68,6 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) } ``` -*** - Now generate a migration (`dotnet ef migrations add ....`), and open it with your favorite editor, adding the following: ```c# From da4ce5688aae9201827df0f306ede5d3f2f04659 Mon Sep 17 00:00:00 2001 From: Nirvin M Date: Mon, 30 Nov 2020 17:09:05 +0530 Subject: [PATCH 049/207] Minor typo fixes in code --- docs/mapping/full-text-search.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/mapping/full-text-search.md b/docs/mapping/full-text-search.md index fc84ca1eb7..43f4471170 100644 --- a/docs/mapping/full-text-search.md +++ b/docs/mapping/full-text-search.md @@ -48,11 +48,12 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity() .HasGeneratedTsVectorColumn( - p => b.TsVector, + p => p.TsVector, "english", // Text search config p => new { p.Name, p.Description }) // Included properties - .HasIndex(b => b.TsVector) + .HasIndex(p => p.TsVector) .HasMethod("GIN"); // Index method on the search vector (GIN or GIST) +} ``` #### [Older Versions](#tab/older) From daaf8541c089c0cf4dcfb5f5b620f08acd21801b Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Tue, 5 Jan 2021 11:45:19 +0100 Subject: [PATCH 050/207] Add note on patching migrations for computed columns --- docs/release-notes/5.0.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/release-notes/5.0.md b/docs/release-notes/5.0.md index 528b6ad02b..5fdac3a55b 100644 --- a/docs/release-notes/5.0.md +++ b/docs/release-notes/5.0.md @@ -43,6 +43,8 @@ modelBuilder.Entity() .HasComputedColumnSql("...", stored: true); ``` +If you have existing migrations which were created with previous versions of EF Core, the column definitions in those also need to be fixed up with `stored: true`. + ### IsCreatedConcurrently defaults to true ([#1212](https://github.com/npgsql/efcore.pg/issues/1212)) Previously, when `IsCreatedConcurrently` was used to configure an index without parameters, the default was `false` - this has changed to `true`. Note that indexes are never configured for for concurrent creation unless `IsCreatedConcurrently` is specified. From 522470bfad558c333f524088bc1658d0f5da85be Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Mon, 18 Jan 2021 13:08:41 +0100 Subject: [PATCH 051/207] Document Npgsql.EntityFrameworkCore.PostgreSQL.Trigrams --- docs/mapping/translations.md | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/docs/mapping/translations.md b/docs/mapping/translations.md index c928d86fee..416446cdb4 100644 --- a/docs/mapping/translations.md +++ b/docs/mapping/translations.md @@ -146,6 +146,30 @@ EF.Functions.Reverse(value) | reverse(value) Regex.IsMatch(stringValue, "^A+") | [stringValue ~ '^A+'](http://www.postgresql.org/docs/current/static/functions-matching.html#FUNCTIONS-POSIX-REGEXP) (with options) Regex.IsMatch(stringValue, "^A+", regexOptions) | [stringValue ~ '^A+'](http://www.postgresql.org/docs/current/static/functions-matching.html#FUNCTIONS-POSIX-REGEXP) (with options) +## Trigram functions + +The below translations provide functionality for determining the similarity of alphanumeric text based on trigram matching, using the [`pg_trgm`](https://www.postgresql.org/docs/current/pgtrgm.html) extension which is bundled with standard PostgreSQL distributions. All the below parameters are strings. + +> [!NOTE] +> To use these translations, your project must depend on the [Npgsql.EntityFrameworkCore.PostgreSQL.Trigrams](https://www.nuget.org/packages/Npgsql.EntityFrameworkCore.PostgreSQL.Trigrams/) package, and call in your `OnModelConfiguring`. + +.NET | SQL +----------------------------------------------------------------- | -------------------- +EF.Functions.TrigramsShow(s) | show_trgm(s) +EF.Functions.TrigramsSimilarity(s1, s2) | similarity(s1, s2) +EF.Functions.TrigramsWordSimilarity(s1, s2) | word_similarity(s1, s2) +EF.Functions.TrigramsStrictWordSimilarity(s1, s2) | strict_word_similarity(s1, s2) +EF.Functions.TrigramsAreSimilar(s1, s2) | s1 % s2 +EF.Functions.TrigramsAreWordSimilar(s1, s2) | s1 <% s2 +EF.Functions.TrigramsAreNotWordSimilar(s1, s2) | s1 %> s2 +EF.Functions.TrigramsAreStrictWordSimilar(s1, s2) | s1 <<% s2 +EF.Functions.TrigramsAreNotStrictWordSimilar(s1, s2) | s1 %>> s2 +EF.Functions.TrigramsSimilarityDistance(s1, s2) | s1 <-> s2 +EF.Functions.TrigramsWordSimilarityDistance(s1, s2) | s1 <<-> s2 +EF.Functions.TrigramsWordSimilarityDistanceInverted(s1, s2) | s1 <->> s2 +EF.Functions.TrigramsStrictWordSimilarityDistance(s1, s2) | s1 <<<-> s2 +EF.Functions.TrigramsStrictWordSimilarityDistanceInverted(s1, s2) | s1 <->>> s2 + ## Miscellaneous functions .NET | SQL From 178c1530ac85cb83304cec129c6328d230afdfc8 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Sun, 31 Jan 2021 16:57:28 +0100 Subject: [PATCH 052/207] Document ltree support in EFCore.PG (#76) See https://github.com/npgsql/efcore.pg/issues/1592 --- docs/mapping/translations.md | 33 ++++++++++++++++++++++++++++++++- 1 file changed, 32 insertions(+), 1 deletion(-) diff --git a/docs/mapping/translations.md b/docs/mapping/translations.md index 416446cdb4..5d14c11307 100644 --- a/docs/mapping/translations.md +++ b/docs/mapping/translations.md @@ -151,7 +151,7 @@ Regex.IsMatch(stringValue, "^A+", regexOptions) | [stringValue ~ ' The below translations provide functionality for determining the similarity of alphanumeric text based on trigram matching, using the [`pg_trgm`](https://www.postgresql.org/docs/current/pgtrgm.html) extension which is bundled with standard PostgreSQL distributions. All the below parameters are strings. > [!NOTE] -> To use these translations, your project must depend on the [Npgsql.EntityFrameworkCore.PostgreSQL.Trigrams](https://www.nuget.org/packages/Npgsql.EntityFrameworkCore.PostgreSQL.Trigrams/) package, and call in your `OnModelConfiguring`. +> Prior to version 6.0, to use these translations, your project must depend on the [Npgsql.EntityFrameworkCore.PostgreSQL.Trigrams](https://www.nuget.org/packages/Npgsql.EntityFrameworkCore.PostgreSQL.Trigrams/) package, and call in your `OnModelConfiguring`. .NET | SQL ----------------------------------------------------------------- | -------------------- @@ -170,6 +170,37 @@ EF.Functions.TrigramsWordSimilarityDistanceInverted(s1, s2) | s1 <-> EF.Functions.TrigramsStrictWordSimilarityDistance(s1, s2) | s1 <<<-> s2 EF.Functions.TrigramsStrictWordSimilarityDistanceInverted(s1, s2) | s1 <->>> s2 +## LTree functions + +The below translations are for working with label trees from the PostgreSQL [`ltree`](https://www.postgresql.org/docs/current/ltree.html) extension. Use the type to represent ltree and invoke methods on it in EF Core LINQ queries. + +> [!NOTE] +> LTree support was introduced in version 6.0 of the provider. + +.NET | SQL +----------------------------------------------------------------- | -------------------- +ltree1.IsAncestorOf(ltree2) | ltree1 @> ltree2 +ltree1.IsDescendant(ltree2) | ltree1 <@ ltree2 +ltree.MatchesLQuery(lquery) | ltree ~ lquery +ltree.MatchesLTxtQuery(ltxtquery) | ltree @ ltxtquery +lqueries.Any(q => ltree.MatchesLQuery(q)) | ltree ? lqueries +ltrees.Any(t => t.IsAncestorOf(ltree)) | ltrees @> ltree +ltrees.Any(t => t.IsDescendant(ltree)) | ltrees <@ ltree +ltrees.Any(t => t.MatchesLQuery(lquery)) | ltrees ~ ltree +ltrees.Any(t => t.MatchesLTxtQuery(ltxtquery)) | ltrees @ ltxtquery +ltrees.Any(t => lqueries.Any(q => t.MatchesLQuery(q))) | ltrees ? lqueries +ltrees.FirstOrDefault(l => l.IsAncestorOf(ltree)) | ltrees ?@> ltree +ltrees.FirstOrDefault(l => l.IsDescendant(ltree)) | ltrees ?<@ ltree +ltrees.FirstOrDefault(l => l.MatchesLQuery(lquery)) | ltrees ?~ ltree +ltrees.FirstOrDefault(l => l.MatchesLTxtQuery(ltxtquery)) | ltrees ?@ ltree +ltree.Subtree(0, 1) | subltree(ltree, 0, 1) +ltree.Subpath(0, 1) | sublpath(ltree, 0, 1) +ltree.Subpath(2) | sublpath(ltree, 2) +ltree.NLevel | nlevel(ltree) +ltree.Index(subpath) | index(ltree, subpath) +ltree.Index(subpath, 2) | index(ltree, subpath, 2) +LTree.LongestCommonAncestor(ltree1, ltree2) | lca(index(ltree1, ltree2) + ## Miscellaneous functions .NET | SQL From 63f61b4b7886faa2a22d28ac168665804543490c Mon Sep 17 00:00:00 2001 From: Bouke Haarsma Date: Mon, 15 Feb 2021 17:11:08 +0100 Subject: [PATCH 053/207] Incorrect mapping for non-POCO Fluent example (#78) --- docs/mapping/json.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/mapping/json.md b/docs/mapping/json.md index 93453d51f7..d6989b4810 100644 --- a/docs/mapping/json.md +++ b/docs/mapping/json.md @@ -44,7 +44,7 @@ class MyContext : DbContext public class SomeEntity { public int Id { get; set; } - public Customer Customer { get; set; } + public string Customer { get; set; } } ``` From edf25ba651f062500affef2ce18a61ff02d079b4 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Fri, 19 Feb 2021 13:06:54 +0100 Subject: [PATCH 054/207] EFCore.PG 6.0 breaking change note on arrays and value converters See https://github.com/npgsql/efcore.pg/issues/1716 --- docs/release-notes/6.0.md | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 docs/release-notes/6.0.md diff --git a/docs/release-notes/6.0.md b/docs/release-notes/6.0.md new file mode 100644 index 0000000000..f47df2d552 --- /dev/null +++ b/docs/release-notes/6.0.md @@ -0,0 +1,21 @@ +# 6.0 Release Notes + +Version 6.0 of the Npgsql Entity Framework Core provider is in development, and will be released at the same time as EF Core 6.0. Monthly previews are available on nuget.org, which work with the corresponding EF Core preview. + +## Breaking changes + +### Value converters for array/list properties need to use a specia new API + +Previously, it was possible to configure value converters for array/list properties with the general EF Core API: + +```c# +modelBuilder.Entity.Property(e => e.ValueConvertedArray) + .HasConversion(w => w.Select(x => x.Value).ToArray(), v => v.Select(x => new IntWrapper(x)).ToArray()); +``` + +This is no longer possible and will cause an exception to be thrown. Instead, use the new `HasPostgresArrayConversion` API, providing conversion lambdas for the array's *elements*: + +```c# +modelBuilder.Entity.Property(e => e.ValueConvertedArray) + .HasPostgresArrayConversion(w => w.Value, v => new IntWrapper(v)); +``` From a4a4469416a11006bd6e3462c5f94ee485e3993a Mon Sep 17 00:00:00 2001 From: Bouke Haarsma Date: Mon, 22 Feb 2021 15:21:30 +0100 Subject: [PATCH 055/207] Expression index requires v5 (not PG12) (#82) --- docs/mapping/full-text-search.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/mapping/full-text-search.md b/docs/mapping/full-text-search.md index 43f4471170..dab60814eb 100644 --- a/docs/mapping/full-text-search.md +++ b/docs/mapping/full-text-search.md @@ -110,7 +110,7 @@ var npgsql = context.Products Version 5.0.0 of the provider includes sugar for defining the appropriate expression index; if you're using an older version, you'll have to define a raw SQL migration yourself. -#### [PostgreSQL 12+](#tab/pg12) +#### [Version 5.0.0](#tab/v5) ```c# modelBuilder.Entity() From 20c160a17da6f8e12a2f8b5ba55d82af6a9a672b Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Fri, 5 Mar 2021 11:38:11 +0100 Subject: [PATCH 056/207] Add disposal information for JsonDocument --- docs/mapping/json.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/docs/mapping/json.md b/docs/mapping/json.md index d6989b4810..e573032f3c 100644 --- a/docs/mapping/json.md +++ b/docs/mapping/json.md @@ -147,14 +147,16 @@ This provides a seamless mapping approach, and supports embedding nested types a If your column JSON schema isn't stable, a strongly-typed POCO mapping may not be appropriate. The Npgsql provider also allows you to map the DOM document type provided by [System.Text.Json APIs](https://devblogs.microsoft.com/dotnet/try-the-new-system-text-json-apis/). ```c# -public class SomeEntity +public class SomeEntity : IDisposable { public int Id { get; set; } public JsonDocument Customer { get; set; } + + public void Dispose() => Customer?.Dispose(); } ``` -Note that neither a data annotation nor the fluent API are required, as `JsonDocument` is automatically recognized and mapped to `jsonb`. +Note that neither a data annotation nor the fluent API are required, as [JsonDocument](https://docs.microsoft.com/dotnet/api/system.text.json.jsondocument) is automatically recognized and mapped to `jsonb`. Note also that `JsonDocument` is disposable, so the entity type is made disposable as well; not dispose the `JsonDocument` will result in the memory not being returned to the pool, which will increase GC impact across various parts of the framework. Once a document is loaded from the database, you can traverse it: From 213a369ef64da157fea34d0f87a57b2514d6ee87 Mon Sep 17 00:00:00 2001 From: Bouke Haarsma Date: Mon, 12 Apr 2021 17:12:40 +0200 Subject: [PATCH 057/207] Fix typo (#94) --- docs/mapping/translations.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/mapping/translations.md b/docs/mapping/translations.md index 5d14c11307..57ec4dccd9 100644 --- a/docs/mapping/translations.md +++ b/docs/mapping/translations.md @@ -28,7 +28,7 @@ dateTime.AddSeconds(1) | [dateTime + INTERVAL '1 seconds'](https://www.p dateTime.AddYears(1) | [dateTime + INTERVAL '1 years'](https://www.postgresql.org/docs/current/functions-datetime.html#OPERATORS-DATETIME-TABLE) dateTime.Date | [date_trunc('day', dateTime)](https://www.postgresql.org/docs/current/functions-datetime.html) dateTime.Day | [date_part('day', dateTime)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) -dateTime.DayOfWeek | [floor(date_part('dow', o.""OrderDate""))::INT](https://www.postgresql.org/docs/current/functions-datetime.html) +dateTime.DayOfWeek | [floor(date_part('dow', dateTime))::INT](https://www.postgresql.org/docs/current/functions-datetime.html) dateTime.DayOfYear | [date_part('doy', dateTime)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) dateTime.Hour | [date_part('hour', dateTime)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) dateTime.Minute | [date_part('minute', dateTime)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) From 544b8b96873d20f410d8bc8c081e2af2726142cd Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Wed, 14 Apr 2021 11:21:39 +0200 Subject: [PATCH 058/207] Add note on mapping enums with schemas in EF Core See https://github.com/npgsql/efcore.pg/issues/930 --- docs/mapping/enum.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/mapping/enum.md b/docs/mapping/enum.md index c1776e2938..f7f9c2bb0f 100644 --- a/docs/mapping/enum.md +++ b/docs/mapping/enum.md @@ -47,7 +47,7 @@ static MyDbContext() => NpgsqlConnection.GlobalTypeMapper.MapEnum(); ``` -This code lets Npgsql know that your CLR enum type, `Mood`, should be mapped to a database enum called `Mood`. +This code lets Npgsql know that your CLR enum type, `Mood`, should be mapped to a database enum called `Mood`. Note that if your enum is in a custom schema (not `public`), you must specify that schema in the call to `MapEnum`. If you're curious as to inner workings, this code maps the enum with the ADO.NET provider - [see here for the full docs](http://www.npgsql.org/doc/types/enums_and_composites.html). When the Npgsql EF Core first initializes, it calls into the ADO.NET provider to get all mapped enums, and sets everything up internally at the EF Core layer as well. From 4043c10181fa6b7da173f472e9092aceb388c3f9 Mon Sep 17 00:00:00 2001 From: Addison Beck Date: Wed, 14 Apr 2021 11:53:36 -0400 Subject: [PATCH 059/207] Update collations-and-case-sensitivity.md (#95) Minor typo. The code examples uses the name "my_collation" but the descriptions calls it "some_collation". --- docs/misc/collations-and-case-sensitivity.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/misc/collations-and-case-sensitivity.md b/docs/misc/collations-and-case-sensitivity.md index 03f0ed1166..cd1d9c3d14 100644 --- a/docs/misc/collations-and-case-sensitivity.md +++ b/docs/misc/collations-and-case-sensitivity.md @@ -22,7 +22,7 @@ In PostgreSQL, collations are first-class, named database objects which can be c modelBuilder.HasCollation("my_collation", locale: "en-u-ks-primary", provider: "icu", deterministic: false); ``` -This creates a collation with the name `some_collation`: this is an arbitrary name you can choose, which you will be specifying later when assigning the collation to columns. The rest of the parameters instruct PostgreSQL to create a non-deterministic, case-insensitive ICU collation. ICU collations are very powerful, and allow you to specify precise rules with regards to case, accents and other textual aspects. Consult [the ICU docs](http://userguide.icu-project.org/collation) for more information on supported features and keywords. +This creates a collation with the name `my_collation`: this is an arbitrary name you can choose, which you will be specifying later when assigning the collation to columns. The rest of the parameters instruct PostgreSQL to create a non-deterministic, case-insensitive ICU collation. ICU collations are very powerful, and allow you to specify precise rules with regards to case, accents and other textual aspects. Consult [the ICU docs](http://userguide.icu-project.org/collation) for more information on supported features and keywords. ### Column collation From 84851af5bad0d29b32116555296e5da81a614f5e Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Wed, 28 Apr 2021 11:24:20 +0200 Subject: [PATCH 060/207] Add some NTS translations * https://github.com/npgsql/efcore.pg/issues/1827 * https://github.com/npgsql/efcore.pg/issues/1638 * https://github.com/npgsql/efcore.pg/issues/1084 --- docs/mapping/nts.md | 122 +++++++++++++++++++++++--------------------- 1 file changed, 63 insertions(+), 59 deletions(-) diff --git a/docs/mapping/nts.md b/docs/mapping/nts.md index ca3025ec9c..bfd3906683 100644 --- a/docs/mapping/nts.md +++ b/docs/mapping/nts.md @@ -85,62 +85,66 @@ The following table lists NetTopologySuite operations which are translated to Po Note that the plugin is far from covering all spatial operations. If an operation you need is missing, please open an issue to request for it. -.NET | SQL ----------------------------------|----- -geom.Area() | [ST_Area(geom)](https://postgis.net/docs/manual-3.0/ST_Area.html) -geom.AsBinary() | [ST_AsBinary(geom)](https://postgis.net/docs/manual-3.0/ST_AsBinary.html) -geom.AsText() | [ST_AsText(geom)](https://postgis.net/docs/manual-3.0/ST_AsText.html) -geom.Boundary | [ST_Boundary(geom)](https://postgis.net/docs/manual-3.0/ST_Boundary.html) -geom.Buffer(d) | [ST_Buffer(geom,d)](https://postgis.net/docs/manual-3.0/ST_Buffer.html) -geom.Centroid | [ST_Centroid(geom)](https://postgis.net/docs/manual-3.0/ST_Centroid.html) -geom1.Contains(geom2)) | [ST_Contains(geom1, geom2)](https://postgis.net/docs/manual-3.0/ST_Contains.html) -geomCollection.Count | [ST_NumGeometries(geom1)](https://postgis.net/docs/manual-3.0/ST_NumGeometries.html) -linestring.Count | [ST_NumPoints(linestring)](https://postgis.net/docs/manual-3.0/ST_NumPoints.html) -geom1.ConvexHull() | [ST_ConvexHull(geom1)](https://postgis.net/docs/manual-3.0/ST_ConvexHull.html) -geom1.Covers(geom2)) | [ST_Covers(geom1, geom2)](https://postgis.net/docs/manual-3.0/ST_Covers.html) -geom1.CoveredBy(geom2)) | [ST_CoveredBy(geom1, geom2)](https://postgis.net/docs/manual-3.0/ST_CoveredBy.html) -geom1.Crosses(geom2) | [ST_Crosses(geom1, geom2)](https://postgis.net/docs/manual-3.0/ST_Crosses.html) -geom1.Difference(geom2) | [ST_Difference(geom1, geom2)](https://postgis.net/docs/manual-3.0/ST_Difference.html) -geom1.Dimension | [ST_Dimension(geom1)](https://postgis.net/docs/manual-3.0/ST_Dimension.html) -geom1.Disjoint(geom2)) | [ST_Disjoint(geom1, geom2)](https://postgis.net/docs/manual-3.0/ST_Disjoint.html) -geom1.Distance(geom2) | [ST_Distance(geom1, geom2)](https://postgis.net/docs/manual-3.0/ST_Distance.html) -geom1.Envelope | [ST_Envelope(geom1)](https://postgis.net/docs/manual-3.0/ST_Envelope.html) -geom1.ExactEquals(geom2) | [ST_OrderingEquals(geom1, geom2)](https://postgis.net/docs/manual-3.0/ST_OrderingEquals.html) -lineString.EndPoint | [ST_EndPoint(lineString)](https://postgis.net/docs/manual-3.0/ST_EndPoint.html) -polygon.ExteriorRing | [ST_ExteriorRing(polygon)](https://postgis.net/docs/manual-3.0/ST_ExteriorRing.html) -geom1.Equals(geom2) | [geom1 = geom2](https://postgis.net/docs/manual-3.0/ST_Geometry_EQ.html) -geom1.Polygon.EqualsExact(geom2) | [geom1 = geom2](https://postgis.net/docs/manual-3.0/ST_Geometry_EQ.html) -geom1.EqualsTopologically(geom2) | [ST_Equals(geom1, geom2)](https://postgis.net/docs/manual-3.0/ST_Equals.html) -geom.GeometryType | [GeometryType(geom)](https://postgis.net/docs/manual-3.0/GeometryType.html) -geomCollection.GetGeometryN(i) | [ST_GeometryN(geomCollection, i)](https://postgis.net/docs/manual-3.0/ST_GeometryN.html) -linestring.GetPointN(i) | [ST_PointN(linestring, i)](https://postgis.net/docs/manual-3.0/ST_PointN.html) -geom1.Intersection(geom2) | [ST_Intersection(geom1, geom2)](https://postgis.net/docs/manual-3.0/ST_Intersection.html) -geom1.Intersects(geom2) | [ST_Intersects(geom1, geom2)](https://postgis.net/docs/manual-3.0/ST_Intersects.html) -geom.InteriorPoint | [ST_PointOnSurface(geom)](https://postgis.net/docs/manual-3.0/ST_PointOnSurface.html) -lineString.IsClosed() | [ST_IsClosed(lineString)](https://postgis.net/docs/manual-3.0/ST_IsClosed.html) -geomCollection.IsEmpty() | [ST_IsEmpty(geomCollection)](https://postgis.net/docs/manual-3.0/ST_IsEmpty.html) -linestring.IsRing | [ST_IsRing(linestring)](https://postgis.net/docs/manual-3.0/ST_IsRing.html) -geom.IsWithinDistance(geom2,d) | [ST_DWithin(geom1,geom2,d)](https://postgis.net/docs/manual-3.0/ST_DWithin.html) -geom.IsSimple() | [ST_IsSimple(geom)](https://postgis.net/docs/manual-3.0/ST_IsSimple.html) -geom.IsValid() | [ST_IsValid(geom)](https://postgis.net/docs/manual-3.0/ST_IsValid.html) -lineString.Length | [ST_Length(lineString)](https://postgis.net/docs/manual-3.0/ST_Length.html) -geom.Normalized | [ST_Normalize(geom)](https://postgis.net/docs/manual-3.0/ST_Normalize.html) -geomCollection.NumGeometries | [ST_NumGeometries(geomCollection)](https://postgis.net/docs/manual-3.0/ST_NumGeometries.html) -polygon.NumInteriorRings | [ST_NumInteriorRings(polygon)](https://postgis.net/docs/manual-3.0/ST_NumInteriorRings.html) -lineString.NumPoints | [ST_NumPoints(lineString)](https://postgis.net/docs/manual-3.0/ST_NumPoints.html) -geom1.Overlaps(geom2)) | [ST_Overlaps(geom1, geom2)](https://postgis.net/docs/manual-3.0/ST_Overlaps.html) -geom.PointOnSurface | [ST_PointOnSurface(geom)](https://postgis.net/docs/manual-3.0/ST_PointOnSurface.html) -geom1.Relate(geom2) | [ST_Relate(geom1, geom2)](https://postgis.net/docs/manual-3.0/ST_Relate.html) -geom.Reverse() | [ST_Reverse(geom)](https://postgis.net/docs/manual-3.0/ST_Reverse.html) -geom1.SRID | [ST_SRID(geom1)](https://postgis.net/docs/manual-3.0/ST_SRID.html) -lineString.StartPoint | [ST_StartPoint(lineString)](https://postgis.net/docs/manual-3.0/ST_StartPoint.html) -geom1.SymmetricDifference(geom2) | [ST_SymDifference(geom1, geom2)](https://postgis.net/docs/manual-3.0/ST_SymDifference.html) -geom.ToBinary() | [ST_AsBinary(geom)](https://postgis.net/docs/manual-3.0/ST_AsBinary.html) -geom.ToText() | [ST_AsText(geom)](https://postgis.net/docs/manual-3.0/ST_AsText.html) -geom1.Touches(geom2)) | [ST_Touches(geom1, geom2)](https://postgis.net/docs/manual-3.0/ST_Touches.html) -geom1.Union(geom2) | [ST_Union(geom1, geom2)](https://postgis.net/docs/manual-3.0/ST_Union.html) -geom1.Within(geom2) | [ST_Within(geom1, geom2)](https://postgis.net/docs/manual-3.0/ST_Within.html) -point.M | [ST_M(point)](https://postgis.net/docs/manual-3.0/ST_M.html) -point.X | [ST_X(point)](https://postgis.net/docs/manual-3.0/ST_X.html) -point.Y | [ST_Y(point)](https://postgis.net/docs/manual-3.0/ST_Y.html) -point.Z | [ST_Z(point)](https://postgis.net/docs/manual-3.0/ST_Z.html) +.NET | SQL +---------------------------------------------------------------- |----- +geom.Area() | [ST_Area(geom)](https://postgis.net/docs/ST_Area.html) +geom.AsBinary() | [ST_AsBinary(geom)](https://postgis.net/docs/ST_AsBinary.html) +geom.AsText() | [ST_AsText(geom)](https://postgis.net/docs/ST_AsText.html) +geom.Boundary | [ST_Boundary(geom)](https://postgis.net/docs/ST_Boundary.html) +geom.Buffer(d) | [ST_Buffer(geom,d)](https://postgis.net/docs/ST_Buffer.html) +geom.Centroid | [ST_Centroid(geom)](https://postgis.net/docs/ST_Centroid.html) +geom1.Contains(geom2) | [ST_Contains(geom1, geom2)](https://postgis.net/docs/ST_Contains.html) +geomCollection.Count | [ST_NumGeometries(geom1)](https://postgis.net/docs/ST_NumGeometries.html) +linestring.Count | [ST_NumPoints(linestring)](https://postgis.net/docs/ST_NumPoints.html) +geom1.ConvexHull() | [ST_ConvexHull(geom1)](https://postgis.net/docs/ST_ConvexHull.html) +geom1.Covers(geom2) | [ST_Covers(geom1, geom2)](https://postgis.net/docs/ST_Covers.html) +geom1.CoveredBy(geom2) | [ST_CoveredBy(geom1, geom2)](https://postgis.net/docs/ST_CoveredBy.html) +geom1.Crosses(geom2) | [ST_Crosses(geom1, geom2)](https://postgis.net/docs/ST_Crosses.html) +geom1.Difference(geom2) | [ST_Difference(geom1, geom2)](https://postgis.net/docs/ST_Difference.html) +geom1.Dimension | [ST_Dimension(geom1)](https://postgis.net/docs/ST_Dimension.html) +geom1.Disjoint(geom2) | [ST_Disjoint(geom1, geom2)](https://postgis.net/docs/ST_Disjoint.html) +geom1.Distance(geom2) | [ST_Distance(geom1, geom2)](https://postgis.net/docs/ST_Distance.html) +EF.Functions.DistanceKnn(geom1, geom2) (v6) | [geom1 <-> geom2](https://postgis.net/docs/geometry_distance_knn.html) +EF.Functions.Distance(geom1, geom2, useSpheriod) (v6) | [ST_Distance(geom1, geom2, useSpheriod)](https://postgis.net/docs/ST_Distance.html) +geom1.Envelope | [ST_Envelope(geom1)](https://postgis.net/docs/ST_Envelope.html) +geom1.ExactEquals(geom2) | [ST_OrderingEquals(geom1, geom2)](https://postgis.net/docs/ST_OrderingEquals.html) +lineString.EndPoint | [ST_EndPoint(lineString)](https://postgis.net/docs/ST_EndPoint.html) +polygon.ExteriorRing | [ST_ExteriorRing(polygon)](https://postgis.net/docs/ST_ExteriorRing.html) +geom1.Equals(geom2) | [geom1 = geom2](https://postgis.net/docs/ST_Geometry_EQ.html) +geom1.Polygon.EqualsExact(geom2) | [geom1 = geom2](https://postgis.net/docs/ST_Geometry_EQ.html) +geom1.EqualsTopologically(geom2) | [ST_Equals(geom1, geom2)](https://postgis.net/docs/ST_Equals.html) +geom.GeometryType | [GeometryType(geom)](https://postgis.net/docs/GeometryType.html) +geomCollection.GetGeometryN(i) | [ST_GeometryN(geomCollection, i)](https://postgis.net/docs/ST_GeometryN.html) +linestring.GetPointN(i) | [ST_PointN(linestring, i)](https://postgis.net/docs/ST_PointN.html) +geom1.Intersection(geom2) | [ST_Intersection(geom1, geom2)](https://postgis.net/docs/ST_Intersection.html) +geom1.Intersects(geom2) | [ST_Intersects(geom1, geom2)](https://postgis.net/docs/ST_Intersects.html) +geom.InteriorPoint | [ST_PointOnSurface(geom)](https://postgis.net/docs/ST_PointOnSurface.html) +lineString.IsClosed() | [ST_IsClosed(lineString)](https://postgis.net/docs/ST_IsClosed.html) +geomCollection.IsEmpty() | [ST_IsEmpty(geomCollection)](https://postgis.net/docs/ST_IsEmpty.html) +linestring.IsRing | [ST_IsRing(linestring)](https://postgis.net/docs/ST_IsRing.html) +geom.IsWithinDistance(geom2,d) | [ST_DWithin(geom1, geom2, d)](https://postgis.net/docs/ST_DWithin.html) +EF.Functions.IsWithinDistance(geom1, geom2, d, useSpheriod) (v6) | [ST_DWithin(geom1, geom2, d, useSpheriod)](https://postgis.net/docs/ST_DWithin.html) +geom.IsSimple() | [ST_IsSimple(geom)](https://postgis.net/docs/ST_IsSimple.html) +geom.IsValid() | [ST_IsValid(geom)](https://postgis.net/docs/ST_IsValid.html) +lineString.Length | [ST_Length(lineString)](https://postgis.net/docs/ST_Length.html) +geom.Normalized | [ST_Normalize(geom)](https://postgis.net/docs/ST_Normalize.html) +geomCollection.NumGeometries | [ST_NumGeometries(geomCollection)](https://postgis.net/docs/ST_NumGeometries.html) +polygon.NumInteriorRings | [ST_NumInteriorRings(polygon)](https://postgis.net/docs/ST_NumInteriorRings.html) +lineString.NumPoints | [ST_NumPoints(lineString)](https://postgis.net/docs/ST_NumPoints.html) +geom1.Overlaps(geom2) | [ST_Overlaps(geom1, geom2)](https://postgis.net/docs/ST_Overlaps.html) +geom.PointOnSurface | [ST_PointOnSurface(geom)](https://postgis.net/docs/ST_PointOnSurface.html) +geom1.Relate(geom2) | [ST_Relate(geom1, geom2)](https://postgis.net/docs/ST_Relate.html) +geom.Reverse() | [ST_Reverse(geom)](https://postgis.net/docs/ST_Reverse.html) +geom1.SRID | [ST_SRID(geom1)](https://postgis.net/docs/ST_SRID.html) +lineString.StartPoint | [ST_StartPoint(lineString)](https://postgis.net/docs/ST_StartPoint.html) +geom1.SymmetricDifference(geom2) | [ST_SymDifference(geom1, geom2)](https://postgis.net/docs/ST_SymDifference.html) +geom.ToBinary() | [ST_AsBinary(geom)](https://postgis.net/docs/ST_AsBinary.html) +geom.ToText() | [ST_AsText(geom)](https://postgis.net/docs/ST_AsText.html) +geom1.Touches(geom2) | [ST_Touches(geom1, geom2)](https://postgis.net/docs/ST_Touches.html) +EF.Functions.Transform(geom, srid) | [ST_Transform(geom, srid)](https://postgis.net/docs/ST_Transform.html) +geom1.Union(geom2) | [ST_Union(geom1, geom2)](https://postgis.net/docs/ST_Union.html) +geom1.Within(geom2) | [ST_Within(geom1, geom2)](https://postgis.net/docs/ST_Within.html) +point.M | [ST_M(point)](https://postgis.net/docs/ST_M.html) +point.X | [ST_X(point)](https://postgis.net/docs/ST_X.html) +point.Y | [ST_Y(point)](https://postgis.net/docs/ST_Y.html) +point.Z | [ST_Z(point)](https://postgis.net/docs/ST_Z.html) From d225d6a06ed102fe813b6051aea37fbc6068cb35 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Fri, 14 May 2021 20:42:22 +0200 Subject: [PATCH 061/207] Correct property name in full text search docs --- docs/mapping/full-text-search.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/mapping/full-text-search.md b/docs/mapping/full-text-search.md index dab60814eb..f58a1072e2 100644 --- a/docs/mapping/full-text-search.md +++ b/docs/mapping/full-text-search.md @@ -48,10 +48,10 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity() .HasGeneratedTsVectorColumn( - p => p.TsVector, + p => p.SearchVector, "english", // Text search config p => new { p.Name, p.Description }) // Included properties - .HasIndex(p => p.TsVector) + .HasIndex(p => p.SearchVector) .HasMethod("GIN"); // Index method on the search vector (GIN or GIST) } ``` From a519d12c4055016040cbd04b0bf7063303c9be69 Mon Sep 17 00:00:00 2001 From: Frans Bouma Date: Mon, 7 Jun 2021 15:38:08 +0200 Subject: [PATCH 062/207] Update array.md (#103) The LIKE operator descriptions were wrong, there's no '=' in the expression. --- docs/mapping/array.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/mapping/array.md b/docs/mapping/array.md index 8883184fb3..db8d19aac4 100644 --- a/docs/mapping/array.md +++ b/docs/mapping/array.md @@ -34,7 +34,7 @@ array1.Contains(element)) | [element = ANY(array)](https://w array.Any() | [cardinality(array) > 0](https://www.postgresql.org/docs/current/static/functions-array.html#ARRAY-FUNCTIONS-TABLE) array1.Any(i => array2.Contains(i)) | [array1 && array2](https://www.postgresql.org/docs/current/functions-array.html#ARRAY-OPERATORS-TABLE) array1.All(i => array2.Contains(i)) | [array1 <@ array2](https://www.postgresql.org/docs/current/functions-array.html#ARRAY-OPERATORS-TABLE) -array.Any(s => EF.Functions.Like(string, s)) | [string = LIKE ANY (array)](https://www.postgresql.org/docs/current/functions-comparisons.html#id-1.5.8.30.16) -array.Any(s => EF.Functions.ILike(string, s)) | [string = ILIKE ANY (array)](https://www.postgresql.org/docs/current/functions-comparisons.html#id-1.5.8.30.16) -array.All(s => EF.Functions.Like(string, s)) | [string = LIKE ALL (array)](https://www.postgresql.org/docs/current/functions-comparisons.html#id-1.5.8.30.16) -array.All(s => EF.Functions.ILike(string, s)) | [string = ILIKE ALL (array)](https://www.postgresql.org/docs/current/functions-comparisons.html#id-1.5.8.30.16) +array.Any(s => EF.Functions.Like(string, s)) | [string LIKE ANY (array)](https://www.postgresql.org/docs/current/functions-comparisons.html#id-1.5.8.30.16) +array.Any(s => EF.Functions.ILike(string, s)) | [string ILIKE ANY (array)](https://www.postgresql.org/docs/current/functions-comparisons.html#id-1.5.8.30.16) +array.All(s => EF.Functions.Like(string, s)) | [string LIKE ALL (array)](https://www.postgresql.org/docs/current/functions-comparisons.html#id-1.5.8.30.16) +array.All(s => EF.Functions.ILike(string, s)) | [string ILIKE ALL (array)](https://www.postgresql.org/docs/current/functions-comparisons.html#id-1.5.8.30.16) From f6475ec315eb8b584da64aef11000dc1a4e1823f Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Fri, 24 Sep 2021 10:31:32 +0300 Subject: [PATCH 063/207] EF Core 6.0 release and breaking change notes (#116) Includes documentation on the timestamp handling changes. Closes #115 --- docs/mapping/nodatime.md | 51 ++++++++++++++++- docs/mapping/nts.md | 11 ++-- docs/mapping/translations.md | 88 ++++++++++++++++------------- docs/release-notes/6.0.md | 104 ++++++++++++++++++++++++++++++++++- 4 files changed, 206 insertions(+), 48 deletions(-) diff --git a/docs/mapping/nodatime.md b/docs/mapping/nodatime.md index aef0f714aa..e90f8dfcc2 100644 --- a/docs/mapping/nodatime.md +++ b/docs/mapping/nodatime.md @@ -35,9 +35,9 @@ public class Post var recentPosts = context.Posts.Where(p => p.CreationTime > someInstant); ``` -## Member translation +## Operation translation -Currently, the EF Core provider knows how to translate the most date/time component members of NodaTime's `LocalDateTime`, `LocalDate`, `LocalTime` and `Period`. In other words, the following query will be translated to SQL and evaluated server-side: +The provider knows how to translate many members and methods on mapped NodaTime types. For example, the following query will be translated to SQL and evaluated server-side: ```c# // Get all events which occurred on a Monday @@ -47,4 +47,49 @@ var mondayEvents = context.Events.Where(p => p.SomeDate.DayOfWeek == DayOfWeek.M var oldEvents = context.Events.Where(p => p.SomeDate.Year < 2000); ``` -Note that the plugin is far from covering all translations. If a translation you need is missing, please open an issue to request for it. +Following is the list of supported NodaTime translations; If an operation you need is missing, please open an issue to request for it. + +> [!NOTE] +> Most translations on ZonedDateTime and Period were added in version 6.0 + +.NET | SQL | Notes +------------------------------------------------------- |------------------------------------------------------------------------- | --- +SystemClock.Instance.GetCurrentInstant() | [now()](https://www.postgresql.org/docs/current/functions-datetime.html) +LocalDateTime.Date | [date_trunc('day', timestamp)](https://www.postgresql.org/docs/current/functions-datetime.html) +LocalDateTime.Second (also LocalTime, ZonedDateTime) | [date_part('second', timestamp)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) +LocalDateTime.Minute (also LocalTime, ZonedDateTime) | [date_part('minute', timestamp)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) +LocalDateTime.Hour (also LocalTime, ZonedDateTime) | [date_part('hour', timestamp)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) +LocalDateTime.Day, (also LocalDate, ZonedDateTime) | [date_part('day', timestamp)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) +LocalDateTime.Month (also LocalDate, ZonedDateTime) | [date_part('month', timestamp)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) +LocalDateTime.Year (also LocalDate, ZonedDateTime) | [date_part('year', timestamp)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) +LocalDateTime.DayOfWeek (also LocalDate, ZonedDateTime) | [floor(date_part('dow', timestamp))::INT](https://www.postgresql.org/docs/current/functions-datetime.html) +LocalDateTime.DayOfYear (also LocalDate, ZonedDateTime) | [date_part('doy', timestamp)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) +Period.Seconds (also Duration) | [date_part('second', interval)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) +Period.Minutes (also Duration) | [date_part('minute', interval)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) +Period.Hours (also Duration) | [date_part('hour', interval)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) +Period.Days (also Duration) | [date_part('day', interval)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) +Period.Months | [date_part('month', interval)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) +Period.Years | [date_part('year', interval)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) +Period.FromSeconds | [make_interval(seconds => int)](https://www.postgresql.org/docs/current/functions-datetime.html) +Period.FromMinutes | [make_interval(minutes => int)](https://www.postgresql.org/docs/current/functions-datetime.html) +Period.FromHours | [make_interval(hours => int)](https://www.postgresql.org/docs/current/functions-datetime.html) +Period.FromDays | [make_interval(days => int)](https://www.postgresql.org/docs/current/functions-datetime.html) +Period.FromWeeks | [make_interval(weeks => int)](https://www.postgresql.org/docs/current/functions-datetime.html) +Period.FromMonths | [make_interval(months => int)](https://www.postgresql.org/docs/current/functions-datetime.html) +Period.FromYears | [make_interval(years => int)](https://www.postgresql.org/docs/current/functions-datetime.html) +Duration.TotalMilliseconds | [date_part('epoch', interval) / 0.001](https://www.postgresql.org/docs/current/functions-datetime.html) +Duration.TotalSeconds | [date_part('epoch', interval)](https://www.postgresql.org/docs/current/functions-datetime.html) +Duration.TotalMinutes | [date_part('epoch', interval) / 60.0](https://www.postgresql.org/docs/current/functions-datetime.html) +Duration.TotalDays | [date_part('epoch', interval) / 86400.0](https://www.postgresql.org/docs/current/functions-datetime.html) +Duration.TotalHours | [date_part('epoch', interval) / 3600.0](https://www.postgresql.org/docs/current/functions-datetime.html) +ZonedDateTime.LocalDateTime | [timestamptz AT TIME ZONE 'UTC'](https://www.postgresql.org/docs/current/functions-datetime.html#FUNCTIONS-DATETIME-ZONECONVERT) | Added in 6.0 +DateInterval.Length | [upper(daterange) - lower(daterange)](https://www.postgresql.org/docs/current/functions-range.html) | Added in 6.0 +DateInterval.Start | [lower(daterange)](https://www.postgresql.org/docs/current/functions-range.html) | Added in 6.0 +DateInterval.End | [upper(daterange) - INTERVAL 'P1D'](https://www.postgresql.org/docs/current/functions-range.html) | Added in 6.0 +DateInterval.Contains(LocalDate) | [daterange @> date](https://www.postgresql.org/docs/current/functions-range.html) | Added in 6.0 +DateInterval.Contains(DateInterval) | [daterange @> daterange](https://www.postgresql.org/docs/current/functions-range.html) | Added in 6.0 +DateInterval.Intersection(DateInterval) | [daterange * daterange](https://www.postgresql.org/docs/current/functions-range.html) | Added in 6.0 +DateInterval.Union(DateInterval) | [daterange + daterange](https://www.postgresql.org/docs/current/functions-range.html) | Added in 6.0 +Instant.InUtc | No PG operation (.NET-side conversion from Instant to ZonedDateTime only) | Added in 6.0 + +In addition to the above, most arithmetic operators are also translated (e.g. LocalDate + Period). diff --git a/docs/mapping/nts.md b/docs/mapping/nts.md index bfd3906683..7597273f1a 100644 --- a/docs/mapping/nts.md +++ b/docs/mapping/nts.md @@ -85,8 +85,8 @@ The following table lists NetTopologySuite operations which are translated to Po Note that the plugin is far from covering all spatial operations. If an operation you need is missing, please open an issue to request for it. -.NET | SQL ----------------------------------------------------------------- |----- +.NET | SQL | Notes +---------------------------------------------------------------- |------------------------------------------------------------------------------------- | ----- geom.Area() | [ST_Area(geom)](https://postgis.net/docs/ST_Area.html) geom.AsBinary() | [ST_AsBinary(geom)](https://postgis.net/docs/ST_AsBinary.html) geom.AsText() | [ST_AsText(geom)](https://postgis.net/docs/ST_AsText.html) @@ -104,8 +104,8 @@ geom1.Difference(geom2) | [ST_Differenc geom1.Dimension | [ST_Dimension(geom1)](https://postgis.net/docs/ST_Dimension.html) geom1.Disjoint(geom2) | [ST_Disjoint(geom1, geom2)](https://postgis.net/docs/ST_Disjoint.html) geom1.Distance(geom2) | [ST_Distance(geom1, geom2)](https://postgis.net/docs/ST_Distance.html) -EF.Functions.DistanceKnn(geom1, geom2) (v6) | [geom1 <-> geom2](https://postgis.net/docs/geometry_distance_knn.html) -EF.Functions.Distance(geom1, geom2, useSpheriod) (v6) | [ST_Distance(geom1, geom2, useSpheriod)](https://postgis.net/docs/ST_Distance.html) +EF.Functions.DistanceKnn(geom1, geom2) | [geom1 <-> geom2](https://postgis.net/docs/geometry_distance_knn.html) | Added in 6.0 +EF.Functions.Distance(geom1, geom2, useSpheriod) | [ST_Distance(geom1, geom2, useSpheriod)](https://postgis.net/docs/ST_Distance.html) | Added in 6.0 geom1.Envelope | [ST_Envelope(geom1)](https://postgis.net/docs/ST_Envelope.html) geom1.ExactEquals(geom2) | [ST_OrderingEquals(geom1, geom2)](https://postgis.net/docs/ST_OrderingEquals.html) lineString.EndPoint | [ST_EndPoint(lineString)](https://postgis.net/docs/ST_EndPoint.html) @@ -113,6 +113,7 @@ polygon.ExteriorRing | [ST_ExteriorR geom1.Equals(geom2) | [geom1 = geom2](https://postgis.net/docs/ST_Geometry_EQ.html) geom1.Polygon.EqualsExact(geom2) | [geom1 = geom2](https://postgis.net/docs/ST_Geometry_EQ.html) geom1.EqualsTopologically(geom2) | [ST_Equals(geom1, geom2)](https://postgis.net/docs/ST_Equals.html) +EF.Functions.Force2D | [ST_Force2D(geom)](https://postgis.net/docs/ST_Force2D.html) | Added in 6.0 geom.GeometryType | [GeometryType(geom)](https://postgis.net/docs/GeometryType.html) geomCollection.GetGeometryN(i) | [ST_GeometryN(geomCollection, i)](https://postgis.net/docs/ST_GeometryN.html) linestring.GetPointN(i) | [ST_PointN(linestring, i)](https://postgis.net/docs/ST_PointN.html) @@ -123,7 +124,7 @@ lineString.IsClosed() | [ST_IsClosed( geomCollection.IsEmpty() | [ST_IsEmpty(geomCollection)](https://postgis.net/docs/ST_IsEmpty.html) linestring.IsRing | [ST_IsRing(linestring)](https://postgis.net/docs/ST_IsRing.html) geom.IsWithinDistance(geom2,d) | [ST_DWithin(geom1, geom2, d)](https://postgis.net/docs/ST_DWithin.html) -EF.Functions.IsWithinDistance(geom1, geom2, d, useSpheriod) (v6) | [ST_DWithin(geom1, geom2, d, useSpheriod)](https://postgis.net/docs/ST_DWithin.html) +EF.Functions.IsWithinDistance(geom1, geom2, d, useSpheriod) | [ST_DWithin(geom1, geom2, d, useSpheriod)](https://postgis.net/docs/ST_DWithin.html) | Added in 6.0 geom.IsSimple() | [ST_IsSimple(geom)](https://postgis.net/docs/ST_IsSimple.html) geom.IsValid() | [ST_IsValid(geom)](https://postgis.net/docs/ST_IsValid.html) lineString.Length | [ST_Length(lineString)](https://postgis.net/docs/ST_Length.html) diff --git a/docs/mapping/translations.md b/docs/mapping/translations.md index 57ec4dccd9..c5436375b5 100644 --- a/docs/mapping/translations.md +++ b/docs/mapping/translations.md @@ -6,44 +6,56 @@ The Npgsql-specific translations are listed below. Some areas, such as [full-tex ## Binary functions -.NET | SQL | Added in +.NET | SQL | Notes ---------------------------- | ------------------------------- | -------- -bytes[i] | get_byte(bytes, i) | EF Core 5.0 -bytes.Contains(value) | position(value IN bytes) > 0 | EF Core 5.0 -bytes.Length | length(@bytes) | EF Core 5.0 -bytes1.SequenceEqual(bytes2) | @bytes = @second | EF Core 5.0 +bytes[i] | get_byte(bytes, i) | Added in 5.0 +bytes.Contains(value) | position(value IN bytes) > 0 | Added in 5.0 +bytes.Length | length(@bytes) | Added in 5.0 +bytes1.SequenceEqual(bytes2) | @bytes = @second | Added in 5.0 ## Date and time functions -.NET | SQL ------------------------------- | --- -DateTime.Now | [now()](https://www.postgresql.org/docs/current/functions-datetime.html) -DateTime.Today | [date_trunc('day', now())](https://www.postgresql.org/docs/current/functions-datetime.html) -DateTime.UtcNow | [now() AT TIME ZONE 'UTC'](https://www.postgresql.org/docs/current/functions-datetime.html) -dateTime.AddDays(1) | [dateTime + INTERVAL '1 days'](https://www.postgresql.org/docs/current/functions-datetime.html#OPERATORS-DATETIME-TABLE) -dateTime.AddHours(value) | [dateTime + INTERVAL '1 hours'](https://www.postgresql.org/docs/current/functions-datetime.html#OPERATORS-DATETIME-TABLE) -dateTime.AddMinutes(1) | [dateTime + INTERVAL '1 minutes'](https://www.postgresql.org/docs/current/functions-datetime.html#OPERATORS-DATETIME-TABLE) -dateTime.AddMonths(1) | [dateTime + INTERVAL '1 months'](https://www.postgresql.org/docs/current/functions-datetime.html#OPERATORS-DATETIME-TABLE) -dateTime.AddSeconds(1) | [dateTime + INTERVAL '1 seconds'](https://www.postgresql.org/docs/current/functions-datetime.html#OPERATORS-DATETIME-TABLE) -dateTime.AddYears(1) | [dateTime + INTERVAL '1 years'](https://www.postgresql.org/docs/current/functions-datetime.html#OPERATORS-DATETIME-TABLE) -dateTime.Date | [date_trunc('day', dateTime)](https://www.postgresql.org/docs/current/functions-datetime.html) -dateTime.Day | [date_part('day', dateTime)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) -dateTime.DayOfWeek | [floor(date_part('dow', dateTime))::INT](https://www.postgresql.org/docs/current/functions-datetime.html) -dateTime.DayOfYear | [date_part('doy', dateTime)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) -dateTime.Hour | [date_part('hour', dateTime)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) -dateTime.Minute | [date_part('minute', dateTime)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) -dateTime.Month | [date_part('month', dateTime)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) -dateTime.Second | [date_part('second', dateTime)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) -dateTime.Year | [date_part('year', dateTime)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) -timeSpan.Days | [floor(date_part('day', timeSpan))::INT](https://www.postgresql.org/docs/current/functions-datetime.html) -timeSpan.Hours | [floor(date_part('hour', timeSpan))::INT](https://www.postgresql.org/docs/current/functions-datetime.html) -timeSpan.Minutes | [floor(date_part('minute', timeSpan))::INT](https://www.postgresql.org/docs/current/functions-datetime.html) -timeSpan.Seconds | [floor(date_part('second', timeSpan))::INT](https://www.postgresql.org/docs/current/functions-datetime.html) -timeSpan.Milliseconds | [floor(date_part('millisecond', timeSpan))::INT](https://www.postgresql.org/docs/current/functions-datetime.html) -timeSpan.Milliseconds | [floor(date_part('millisecond', timeSpan))::INT](https://www.postgresql.org/docs/current/functions-datetime.html) -dateTime1 - dateTime2 | [dateTime1 - dateTime2](https://www.postgresql.org/docs/current/functions-datetime.html#OPERATORS-DATETIME-TABLE) -new DateTime(year, month, day) | [make_date(year, month, day)](https://www.postgresql.org/docs/current/functions-datetime.html) -new DateTime(y, m, d, h, m, s) | [make_timestamp(y, m, d, h, m, s)](https://www.postgresql.org/docs/current/functions-datetime.html) +> [!NOTE] +> Since version 6.0, many of the below DateTime translations are also supported on DateTimeOffset. + +.NET | SQL | Notes +------------------------------------ | --------------------------------------------------------------------------------------------------------------------------- | -------- +DateTime.UtcNow (6.0+) | [now()](https://www.postgresql.org/docs/current/functions-datetime.html) | See 6.0 release notes +DateTime.Now (6.0+) | [now()::timestamp](https://www.postgresql.org/docs/current/functions-datetime.html) | See 6.0 release notes +DateTime.Today (6.0+) | [date_trunc('day', now()::timestamp)](https://www.postgresql.org/docs/current/functions-datetime.html) | See 6.0 release notes +DateTime.UtcNow (legacy) | [now() AT TIME ZONE 'UTC'](https://www.postgresql.org/docs/current/functions-datetime.html) | See 6.0 release notes +DateTime.Now (legacy) | [now()](https://www.postgresql.org/docs/current/functions-datetime.html) | See 6.0 release notes +DateTime.Today (legacy) | [date_trunc('day', now())](https://www.postgresql.org/docs/current/functions-datetime.html) | See 6.0 release notes +dateTime.AddDays(1) | [dateTime + INTERVAL '1 days'](https://www.postgresql.org/docs/current/functions-datetime.html#OPERATORS-DATETIME-TABLE) | +dateTime.AddHours(value) | [dateTime + INTERVAL '1 hours'](https://www.postgresql.org/docs/current/functions-datetime.html#OPERATORS-DATETIME-TABLE) | +dateTime.AddMinutes(1) | [dateTime + INTERVAL '1 minutes'](https://www.postgresql.org/docs/current/functions-datetime.html#OPERATORS-DATETIME-TABLE) | +dateTime.AddMonths(1) | [dateTime + INTERVAL '1 months'](https://www.postgresql.org/docs/current/functions-datetime.html#OPERATORS-DATETIME-TABLE) | +dateTime.AddSeconds(1) | [dateTime + INTERVAL '1 seconds'](https://www.postgresql.org/docs/current/functions-datetime.html#OPERATORS-DATETIME-TABLE) | +dateTime.AddYears(1) | [dateTime + INTERVAL '1 years'](https://www.postgresql.org/docs/current/functions-datetime.html#OPERATORS-DATETIME-TABLE) | +dateTime.Date | [date_trunc('day', dateTime)](https://www.postgresql.org/docs/current/functions-datetime.html) | +dateTime.Day | [date_part('day', dateTime)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | +dateTime.DayOfWeek | [floor(date_part('dow', dateTime))::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | +dateTime.DayOfYear | [date_part('doy', dateTime)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | +dateTime.Hour | [date_part('hour', dateTime)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | +dateTime.Minute | [date_part('minute', dateTime)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | +dateTime.Month | [date_part('month', dateTime)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | +dateTime.Second | [date_part('second', dateTime)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | +dateTime.Year | [date_part('year', dateTime)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | +dateTime.ToUniversalTime | [dateTime::timestamptz](https://www.postgresql.org/docs/current/datatype-datetime.html#id-1.5.7.13.18.7) | Added in 6.0 +dateTime.ToLocalTime | [dateTime::timestamp](https://www.postgresql.org/docs/current/datatype-datetime.html#id-1.5.7.13.18.7) | Added in 6.0 +timeSpan.Days | [floor(date_part('day', timeSpan))::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | +timeSpan.Hours | [floor(date_part('hour', timeSpan))::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | +timeSpan.Minutes | [floor(date_part('minute', timeSpan))::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | +timeSpan.Seconds | [floor(date_part('second', timeSpan))::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | +timeSpan.Milliseconds | [floor(date_part('millisecond', timeSpan))::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | +timeSpan.Milliseconds | [floor(date_part('millisecond', timeSpan))::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | +dateTime1 - dateTime2 | [dateTime1 - dateTime2](https://www.postgresql.org/docs/current/functions-datetime.html#OPERATORS-DATETIME-TABLE) | +new DateTime(year, month, day) | [make_date(year, month, day)](https://www.postgresql.org/docs/current/functions-datetime.html) | +new DateTime(y, m, d, h, m, s) | [make_timestamp(y, m, d, h, m, s)](https://www.postgresql.org/docs/current/functions-datetime.html) | +new DateTime(y, m, d, h, m, s, kind) | [make_timestamp or make_timestamptz](https://www.postgresql.org/docs/current/functions-datetime.html), based on `king` | Added in 6.0 + +> [!NOTE] +> See also Npgsql's [NodaTime support](/efcore/mapping/nodatime.html). ## Network functions @@ -109,9 +121,9 @@ Math.Truncate(d) | trunc(d) ## String functions -.NET | SQL | Added in +.NET | SQL | Notes ------------------------------------------------------------- | ------------------------------------------------------ | -------- -EF.Functions.Collate(operand, collation) | operand COLLATE collation | EF Core 5.0 +EF.Functions.Collate(operand, collation) | operand COLLATE collation | Added in 5.0 EF.Functions.Like(matchExpression, pattern) | matchExpression LIKE pattern EF.Functions.Like(matchExpression, pattern, escapeCharacter) | matchExpression LIKE pattern ESCAPE escapeCharacter EF.Functions.ILike(matchExpression, pattern) | [matchExpression ILIKE pattern](../misc/collations-and-case-sensitivity.md) @@ -123,9 +135,9 @@ string.IsNullOrWhiteSpace(value) | value IS NULL OR stringValue.CompareTo(strB) | CASE WHEN stringValue = strB THEN 0 ... END stringValue.Contains(value) | strpos(stringValue, value) > 0 stringValue.EndsWith(value) | stringValue LIKE '%' \|\| value -stringValue.FirstOrDefault() | substr(stringValue, 1, 1) | EF Core 5.0 +stringValue.FirstOrDefault() | substr(stringValue, 1, 1) | Added in 5.0 stringValue.IndexOf(value) | strpos(stringValue, value) - 1 -stringValue.LastOrDefault() | substr(stringValue, length(stringValue), 1) | EF Core 5.0 +stringValue.LastOrDefault() | substr(stringValue, length(stringValue), 1) | Added in 5.0 stringValue.Length | length(stringValue) stringValue.PadLeft(length) | lpad(stringValue, length) stringValue.PadLeft(length, char) | lpad(stringValue, length, char) diff --git a/docs/release-notes/6.0.md b/docs/release-notes/6.0.md index f47df2d552..bc9f33f6fc 100644 --- a/docs/release-notes/6.0.md +++ b/docs/release-notes/6.0.md @@ -1,10 +1,110 @@ # 6.0 Release Notes -Version 6.0 of the Npgsql Entity Framework Core provider is in development, and will be released at the same time as EF Core 6.0. Monthly previews are available on nuget.org, which work with the corresponding EF Core preview. +The release candidate of Npgsql Entity Framework Core provider version 6.0 has been released and is available on nuget. This version works with [version 6.0 of Entity Framework Core](https://docs.microsoft.com/ef/core/what-is-new/ef-core-6.0/whatsnew), and brings new Npgsql features in addition to the general EF Core changes. + +Npgsql 6.0 brings some major breaking changes and is not a simple in-place upgrade. Carefully read the breaking change notes below and upgrade with care. + +## New features + +* Timestamp mapping rationalization and improvements + * Support for `timestamp with time zone` and `timestamp without time zone` has been rationalized and simplified, as well as the DateTime and NodaTime mappings to these database types (see breaking changes below) + * UTC timestamps have been cleanly separated from non-UTC timestamps, aligning with the PostgreSQL types. The former are represented by `timestamp with time zone` and DateTime with Kind UTC, the latter by `timestamp without time zone` and DateTime with Kind Local or Unspecified. It is recommended to use UTC timestamps where possible. + * Npgsql no longer performs any implicit timezone conversions when reading or writing any timestamp value - the value in the database is what you get, and the machine timezone no longer plays any role when reading/writing values. + * Npgsql no longer supports date/time representations which cannot be fully round-tripped to the database. If it can't be fully stored as-is, you can't write it. + * A compatibility switch enables opting out of the new behavior, to maintain backwards compatibility. +* Other date/time improvements + * Support for the new [.NET DateOnly and TimeOnly types](https://devblogs.microsoft.com/dotnet/date-time-and-time-zone-enhancements-in-net-6/). + * Most [DateTimeOffset](https://docs.microsoft.com/dotnet/api/system.datetimeoffset) members and methods are now translated. + * Many NodaTime translations have been added for [ZonedDateTime](https://nodatime.org/3.0.x/api/NodaTime.ZonedDateTime.html), [Period](https://nodatime.org/3.0.x/api/NodaTime.Period.html), [DateInterval](https://nodatime.org/3.0.x/api/NodaTime.DateInterval.html) and others. + * PostgreSQL `daterange` is now mapped to NodaTime [DateInterval](https://nodatime.org/3.0.x/api/NodaTime.DateInterval.html), and most methods on it are translated. +* The provider is now fully annotated for nullable reference types. +* Support for the PostgreSQL [ltree](https://www.postgresql.org/docs/current/ltree.html) type, which represents labels of data stored in a hierarchical tree-like structure. +* Multiple spatial translations have been added for NetTopologySuite ([DistanceKnn, <->](https://github.com/npgsql/efcore.pg/issues/1827), [ST_Force2D](https://github.com/npgsql/efcore.pg/issues/1917), [ST_Distance and ST_DWithin with spheriod](https://github.com/npgsql/efcore.pg/issues/1638)). + +The full list of issues for this release is [available here](https://github.com/npgsql/efcore.pg/milestone/34?closed=1). ## Breaking changes -### Value converters for array/list properties need to use a specia new API +### Major changes to timestamp mapping + +> [!NOTE] +> It is possible to opt out of these changes to maintain backwards compatibility, see below. + +Note: The below notes will use the PostgreSQL aliases `timestamptz` to refer to `timestamp with time zone`, and `timestamp` to refer to `timestamp without time zone`. Note that `timestamptz` represents a UTC timestamp and does not store a timezone in the database. + +* DateTime properties now map to `timestamptz` by default, instead of to `timestamp`; although storing UTC timestamps is the recommended pattern, this will cause the first migration to change your column type. + * If the intention is to store point-in-time or UTC timestamps, it's recommended to allow the migration to occur (see migration notes below). + * If the column really should store non-UTC timestamps (local or unspecified), [explicitly set the column type back to `timestamp`](https://docs.microsoft.com/ef/core/modeling/entity-properties#column-data-types). This is usually discouraged, but can be a temporary solution before transitioning to `timestamptz`. +* It is no longer possible to write DateTime with Kinds Local or Unspecified to `timestamptz` properties (which are the default for DateTime). Previously, Npgsql allowed writing those, performing timezone conversions from local to UTC. To write to `timestamptz`, provide a UTC DateTime. Similarly, it is no longer possible to write DateTime with Kind UTC to a `timestamp` column. +* `timestamptz` values are now read back as DateTime with Kind=UTC, without any conversions; these were previously returned as local DateTime, converted to the local machine's timezone. When reading `timestamptz` values as [DateTimeOffset](https://docs.microsoft.com/dotnet/api/system.datetimeoffset), UTC values (offset 0) are always returned. +* It is no longer possible to write [DateTimeOffset](https://docs.microsoft.com/dotnet/api/system.datetimeoffset) with offsets other than 0 (UTC), since these cannot be represented in PostgreSQL. + +#### NodaTime changes + +* Properties with type [Instant](https://nodatime.org/3.0.x/api/NodaTime.Instant.html) are now mapped to `timestamptz` columns, and not to `timestamp`, since they represent a universally agreed-upon point in time. Although storing UTC timestamps is the recommended pattern, this will cause the first migration to change your column type. + * If the intention is to store point-in-time or UTC timestamps, it's recommended to allow the migration to occur (see migration notes below). + * If the column really should store non-UTC timestamps (local or unspecified), change the property's type to [LocalDateTime](https://nodatime.org/3.0.x/api/NodaTime.LocalDateTime.html) instead; this will maintain the mapping to `timestamp`. This is usually discouraged, but can be a temporary solution before transitioning to `timestamptz`. +* When reading `timestamptz` as [ZonedDateTime](https://nodatime.org/3.0.x/api/NodaTime.ZonedDateTime.html) or [OffsetDateTime](https://nodatime.org/3.0.x/api/NodaTime.OffsetDateTime.html), UTC values are always returned. Previously, local values based on the PostgreSQL `TimeZone` parameter were returned. + +See the Npgsql docs for additional lower-level changes to timestamp handling. + +#### Opting out of the new timestamp mapping logic + +The changes described above are far-reaching, and may break applications in various ways. You can upgrade to version 6.0 but opt out of the new mapping by enabling the `Npgsql.EnableLegacyTimestampBehavior` [AppContext switch](https://docs.microsoft.com/en-us/dotnet/api/system.appcontext?view=net-5.0): + +To revert to the legacy timestamp behavior, add the following at the start of your application, before any EF Core operations are invoked: + +```c# +AppContext.SetSwitch("Npgsql.EnableLegacyTimestampBehavior", true); +``` + +#### Migrating columns from timestamp to timestamptz + +As a result of the above changes, the first migration created after upgrading to 6.0 will alter the columns for all DateTime and Instant properties from `timestamp` to `timestamptz`. If these columns are meant to store point-in-time or UTC timestamps (the recommended practice), then it's best to let this migration proceed; but care must be taken. + +As a starting point, let's assume your existing `timestamp` column has the timestamp `2020-01-01 12:00:00`: + +```sql +SELECT "CreateOn", pg_typeof("CreateOn") AS type FROM "Blogs"; +``` + +Results in: + +```text + CreateOn | type +---------------------+----------------------------- + 2020-01-01 12:00:00 | timestamp without time zone +``` + +The migration generated by version 6.0 will cause the following SQL to be executed: + +```sql +ALTER TABLE "Blogs" ALTER COLUMN "CreateOn" TYPE timestamp with time zone; +``` + +When converting the `timestamp without time zone` column to `timestamp with time zone`, PostgreSQL will assume that existing values are local timestamps, and will convert them to UTC based on the `TimeZone` parameter. Performing the above query will result in something like: + +```text + CreateOn | type +------------------------+-------------------------- + 2020-01-01 12:00:00+02 | timestamp with time zone +``` + +This means that your new `timestamptz` column now contains 10:00 UTC, which is probably not what you want: if the original values were in fact UTC values, you need them to be preserved as-is, with only the column type changing. To do this, edit your migration and add the following to the top of your migration's Up and Down methods: + +```c# +migrationBuilder.Sql("SET TimeZone='UTC'"); +``` + +This will ensure that no time zone conversions will be applied when converting the columns: + +```output + CreateOn | type +------------------------+-------------------------- + 2020-01-01 14:00:00+02 | timestamp with time zone +``` + +### Value converters for array/list properties need to use a special new API Previously, it was possible to configure value converters for array/list properties with the general EF Core API: From 79a0f000acde3deab066890e8cf570b51f07ae38 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Fri, 24 Sep 2021 10:38:13 +0300 Subject: [PATCH 064/207] Fixup to EF Core release notes --- docs/release-notes/6.0.md | 33 ++++++++++++++++++++------------- 1 file changed, 20 insertions(+), 13 deletions(-) diff --git a/docs/release-notes/6.0.md b/docs/release-notes/6.0.md index bc9f33f6fc..3d5554e614 100644 --- a/docs/release-notes/6.0.md +++ b/docs/release-notes/6.0.md @@ -6,17 +6,24 @@ Npgsql 6.0 brings some major breaking changes and is not a simple in-place upgra ## New features -* Timestamp mapping rationalization and improvements - * Support for `timestamp with time zone` and `timestamp without time zone` has been rationalized and simplified, as well as the DateTime and NodaTime mappings to these database types (see breaking changes below) - * UTC timestamps have been cleanly separated from non-UTC timestamps, aligning with the PostgreSQL types. The former are represented by `timestamp with time zone` and DateTime with Kind UTC, the latter by `timestamp without time zone` and DateTime with Kind Local or Unspecified. It is recommended to use UTC timestamps where possible. - * Npgsql no longer performs any implicit timezone conversions when reading or writing any timestamp value - the value in the database is what you get, and the machine timezone no longer plays any role when reading/writing values. - * Npgsql no longer supports date/time representations which cannot be fully round-tripped to the database. If it can't be fully stored as-is, you can't write it. - * A compatibility switch enables opting out of the new behavior, to maintain backwards compatibility. -* Other date/time improvements - * Support for the new [.NET DateOnly and TimeOnly types](https://devblogs.microsoft.com/dotnet/date-time-and-time-zone-enhancements-in-net-6/). - * Most [DateTimeOffset](https://docs.microsoft.com/dotnet/api/system.datetimeoffset) members and methods are now translated. - * Many NodaTime translations have been added for [ZonedDateTime](https://nodatime.org/3.0.x/api/NodaTime.ZonedDateTime.html), [Period](https://nodatime.org/3.0.x/api/NodaTime.Period.html), [DateInterval](https://nodatime.org/3.0.x/api/NodaTime.DateInterval.html) and others. - * PostgreSQL `daterange` is now mapped to NodaTime [DateInterval](https://nodatime.org/3.0.x/api/NodaTime.DateInterval.html), and most methods on it are translated. +### Timestamp rationalization and improvements + +Support for `timestamp with time zone` and `timestamp without time zone` has been rationalized and simplified, and aligned with PostgreSQL best practices. This involves breaking changes, although a compatibility flag can be used to opt out and revert to the previous behavior. + +* UTC timestamps have been cleanly separated from non-UTC timestamps, aligning with the PostgreSQL types. The former are represented by `timestamp with time zone` and DateTime with Kind UTC, the latter by `timestamp without time zone` and DateTime with Kind Local or Unspecified. It is recommended to use UTC timestamps where possible. +* Npgsql no longer performs any implicit timezone conversions when reading or writing any timestamp value - the value in the database is what you get, and the machine timezone no longer plays any role when reading/writing values. +* Npgsql no longer supports date/time representations which cannot be fully round-tripped to the database. If it can't be fully stored as-is, you can't write it. +* A compatibility switch enables opting out of the new behavior, to maintain backwards compatibility. + +Other date/time improvements include: + +* Support for the new [.NET DateOnly and TimeOnly types](https://devblogs.microsoft.com/dotnet/date-time-and-time-zone-enhancements-in-net-6/). +* Most [DateTimeOffset](https://docs.microsoft.com/dotnet/api/system.datetimeoffset) members and methods are now translated. +* Many NodaTime translations have been added for [ZonedDateTime](https://nodatime.org/3.0.x/api/NodaTime.ZonedDateTime.html), [Period](https://nodatime.org/3.0.x/api/NodaTime.Period.html), [DateInterval](https://nodatime.org/3.0.x/api/NodaTime.DateInterval.html) and others. +* PostgreSQL `daterange` is now mapped to NodaTime [DateInterval](https://nodatime.org/3.0.x/api/NodaTime.DateInterval.html), and most methods on it are translated. + +### Other new features + * The provider is now fully annotated for nullable reference types. * Support for the PostgreSQL [ltree](https://www.postgresql.org/docs/current/ltree.html) type, which represents labels of data stored in a hierarchical tree-like structure. * Multiple spatial translations have been added for NetTopologySuite ([DistanceKnn, <->](https://github.com/npgsql/efcore.pg/issues/1827), [ST_Force2D](https://github.com/npgsql/efcore.pg/issues/1917), [ST_Distance and ST_DWithin with spheriod](https://github.com/npgsql/efcore.pg/issues/1638)). @@ -70,7 +77,7 @@ SELECT "CreateOn", pg_typeof("CreateOn") AS type FROM "Blogs"; Results in: -```text +```output CreateOn | type ---------------------+----------------------------- 2020-01-01 12:00:00 | timestamp without time zone @@ -84,7 +91,7 @@ ALTER TABLE "Blogs" ALTER COLUMN "CreateOn" TYPE timestamp with time zone; When converting the `timestamp without time zone` column to `timestamp with time zone`, PostgreSQL will assume that existing values are local timestamps, and will convert them to UTC based on the `TimeZone` parameter. Performing the above query will result in something like: -```text +```output CreateOn | type ------------------------+-------------------------- 2020-01-01 12:00:00+02 | timestamp with time zone From cb93bf7376587b84da6c3f46a8bd7199243e828a Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Fri, 24 Sep 2021 14:18:59 +0300 Subject: [PATCH 065/207] Correct TOC release notes link --- docs/toc.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/toc.yml b/docs/toc.yml index 29000e665b..018feb63c9 100644 --- a/docs/toc.yml +++ b/docs/toc.yml @@ -2,6 +2,8 @@ href: index.md - name: Release notes items: + - name: "6.0" + href: release-notes/6.0.md - name: "5.0" href: release-notes/5.0.md - name: "3.1" From aeeec19cbea3750e2464331d4a6842277883ef72 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Fri, 24 Sep 2021 17:11:40 +0300 Subject: [PATCH 066/207] Npgsql 6.0 release and breaking change notes (#117) --- docs/release-notes/6.0.md | 22 +++++++++++++--------- 1 file changed, 13 insertions(+), 9 deletions(-) diff --git a/docs/release-notes/6.0.md b/docs/release-notes/6.0.md index 3d5554e614..af4012f50d 100644 --- a/docs/release-notes/6.0.md +++ b/docs/release-notes/6.0.md @@ -37,14 +37,16 @@ The full list of issues for this release is [available here](https://github.com/ > [!NOTE] > It is possible to opt out of these changes to maintain backwards compatibility, see below. -Note: The below notes will use the PostgreSQL aliases `timestamptz` to refer to `timestamp with time zone`, and `timestamp` to refer to `timestamp without time zone`. Note that `timestamptz` represents a UTC timestamp and does not store a timezone in the database. +Note: The below notes will use the PostgreSQL aliases `timestamptz` to refer to `timestamp with time zone`, and `timestamp` to refer to `timestamp without time zone`. Note that `timestamp with time zone` represents a UTC timestamp and does **not** store a timezone in the database. * DateTime properties now map to `timestamptz` by default, instead of to `timestamp`; although storing UTC timestamps is the recommended pattern, this will cause the first migration to change your column type. * If the intention is to store point-in-time or UTC timestamps, it's recommended to allow the migration to occur (see migration notes below). * If the column really should store non-UTC timestamps (local or unspecified), [explicitly set the column type back to `timestamp`](https://docs.microsoft.com/ef/core/modeling/entity-properties#column-data-types). This is usually discouraged, but can be a temporary solution before transitioning to `timestamptz`. * It is no longer possible to write DateTime with Kinds Local or Unspecified to `timestamptz` properties (which are the default for DateTime). Previously, Npgsql allowed writing those, performing timezone conversions from local to UTC. To write to `timestamptz`, provide a UTC DateTime. Similarly, it is no longer possible to write DateTime with Kind UTC to a `timestamp` column. * `timestamptz` values are now read back as DateTime with Kind=UTC, without any conversions; these were previously returned as local DateTime, converted to the local machine's timezone. When reading `timestamptz` values as [DateTimeOffset](https://docs.microsoft.com/dotnet/api/system.datetimeoffset), UTC values (offset 0) are always returned. -* It is no longer possible to write [DateTimeOffset](https://docs.microsoft.com/dotnet/api/system.datetimeoffset) with offsets other than 0 (UTC), since these cannot be represented in PostgreSQL. +* It is no longer possible to write [DateTimeOffset](https://docs.microsoft.com/dotnet/api/system.datetimeoffset) with offsets other than 0 (UTC), since these cannot be represented in PostgreSQL. These were previously implicitly converted to UTC before sending. + +See the [Npgsql ADO.NET docs](/doc/release-notes/5.0.html) for additional lower-level changes to timestamp handling. #### NodaTime changes @@ -53,8 +55,6 @@ Note: The below notes will use the PostgreSQL aliases `timestamptz` to refer to * If the column really should store non-UTC timestamps (local or unspecified), change the property's type to [LocalDateTime](https://nodatime.org/3.0.x/api/NodaTime.LocalDateTime.html) instead; this will maintain the mapping to `timestamp`. This is usually discouraged, but can be a temporary solution before transitioning to `timestamptz`. * When reading `timestamptz` as [ZonedDateTime](https://nodatime.org/3.0.x/api/NodaTime.ZonedDateTime.html) or [OffsetDateTime](https://nodatime.org/3.0.x/api/NodaTime.OffsetDateTime.html), UTC values are always returned. Previously, local values based on the PostgreSQL `TimeZone` parameter were returned. -See the Npgsql docs for additional lower-level changes to timestamp handling. - #### Opting out of the new timestamp mapping logic The changes described above are far-reaching, and may break applications in various ways. You can upgrade to version 6.0 but opt out of the new mapping by enabling the `Npgsql.EnableLegacyTimestampBehavior` [AppContext switch](https://docs.microsoft.com/en-us/dotnet/api/system.appcontext?view=net-5.0): @@ -72,13 +72,13 @@ As a result of the above changes, the first migration created after upgrading to As a starting point, let's assume your existing `timestamp` column has the timestamp `2020-01-01 12:00:00`: ```sql -SELECT "CreateOn", pg_typeof("CreateOn") AS type FROM "Blogs"; +SELECT "CreatedOn", pg_typeof("CreatedOn") AS type FROM "Blogs"; ``` Results in: ```output - CreateOn | type + CreatedOn | type ---------------------+----------------------------- 2020-01-01 12:00:00 | timestamp without time zone ``` @@ -86,13 +86,13 @@ Results in: The migration generated by version 6.0 will cause the following SQL to be executed: ```sql -ALTER TABLE "Blogs" ALTER COLUMN "CreateOn" TYPE timestamp with time zone; +ALTER TABLE "Blogs" ALTER COLUMN "CreatedOn" TYPE timestamp with time zone; ``` When converting the `timestamp without time zone` column to `timestamp with time zone`, PostgreSQL will assume that existing values are local timestamps, and will convert them to UTC based on the `TimeZone` parameter. Performing the above query will result in something like: ```output - CreateOn | type + CreatedOn | type ------------------------+-------------------------- 2020-01-01 12:00:00+02 | timestamp with time zone ``` @@ -106,11 +106,15 @@ migrationBuilder.Sql("SET TimeZone='UTC'"); This will ensure that no time zone conversions will be applied when converting the columns: ```output - CreateOn | type + CreatedOn | type ------------------------+-------------------------- 2020-01-01 14:00:00+02 | timestamp with time zone ``` +### NodaTime: daterange is scaffolded as DateInterval by default + +When using NodaTime, a PostgreSQL `daterange` column is scaffolded as a [DateInterval](https://nodatime.org/3.0.x/api/NodaTime.DateInterval.html) property instead of a `NpgsqlRange` property ([#1998](https://github.com/npgsql/efcore.pg/issues/1998)). + ### Value converters for array/list properties need to use a special new API Previously, it was possible to configure value converters for array/list properties with the general EF Core API: From 12b991eaa3f47cab3df0df32dc281a8db33cb4a2 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Tue, 5 Oct 2021 10:23:58 +0200 Subject: [PATCH 067/207] Remove LegacyPostgis (#122) --- docs/mapping/nts.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/mapping/nts.md b/docs/mapping/nts.md index 7597273f1a..900a12c739 100644 --- a/docs/mapping/nts.md +++ b/docs/mapping/nts.md @@ -3,13 +3,13 @@ > [!NOTE] > It's recommended that you start by reading the general [Entity Framework Core docs on spatial support](https://docs.microsoft.com/ef/core/modeling/spatial). -PostgreSQL supports spatial data and operations via [the PostGIS extension](https://postgis.net/), which is a mature and feature-rich database spatial implementation. .NET doesn't provide a standard spatial library, but [NetTopologySuite](https://github.com/NetTopologySuite/NetTopologySuite) is quite a good candidate. The Npgsql EF Core provider has a plugin which allows you to map NetTopologySuite's types PostGIS columns, and even translate many useful spatial operations to SQL. This is the recommended way to interact with spatial types in Npgsql. +PostgreSQL supports spatial data and operations via [the PostGIS extension](https://postgis.net/), which is a mature and feature-rich database spatial implementation. .NET doesn't provide a standard spatial library, but [NetTopologySuite](https://github.com/NetTopologySuite/NetTopologySuite) is a leading spatial library. The Npgsql EF Core provider has a plugin which allows you to map the NTS types to PostGIS columns, allowing seamless reading and writing. This is the recommended way to interact with spatial types in Npgsql. -Note that the EF Core NetTopologySuite plugin depends on [the Npgsql ADO.NET NetTopology plugin](http://www.npgsql.org/doc/types/nts.html), which provides NetTopologySuite support at the lower level. The EF Core plugin automatically arranged for the ADO.NET plugin to be set up. +Note that the EF Core NetTopologySuite plugin depends on [the Npgsql ADO.NET NetTopology plugin](http://www.npgsql.org/doc/types/nts.html), which provides NetTopologySuite support at the lower level. The EF Core plugin automatically sets up the ADO.NET plugin. ## Setup -To set up the NetTopologySuite plugin, add the [Npgsql.EntityFrameworkCore.PostgreSQL.NetTopologySuite nuget](https://www.nuget.org/packages/Npgsql.EntityFrameworkCore.PostgreSQL.NetTopologySuite) to your project. Then, make the following modification to your `UseNpgsql()` line: +To use the NetTopologySuite plugin, add the [Npgsql.EntityFrameworkCore.PostgreSQL.NetTopologySuite nuget](https://www.nuget.org/packages/Npgsql.EntityFrameworkCore.PostgreSQL.NetTopologySuite) to your project. Then, make the following modification to your `UseNpgsql()` line: ```c# protected override void OnConfiguring(DbContextOptionsBuilder builder) @@ -19,7 +19,7 @@ protected override void OnConfiguring(DbContextOptionsBuilder builder) } ``` -This will set up all the necessary mappings and operation translators. In addition, to make sure that the PostGIS extension is installed in your database, add the following to your DbContext: +This sets up all the necessary mappings and operation translators. In addition, to make sure that the PostGIS extension is installed in your database, add the following to your DbContext: ```c# protected override void OnModelCreating(ModelBuilder builder) From 0443e95138acffdb182677ed72393fc986286865 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Tue, 5 Oct 2021 15:49:03 +0200 Subject: [PATCH 068/207] Add note on ltree support requiring PG13 See https://github.com/npgsql/efcore.pg/issues/2025 --- docs/mapping/translations.md | 2 +- docs/release-notes/6.0.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/mapping/translations.md b/docs/mapping/translations.md index c5436375b5..1ffb454f18 100644 --- a/docs/mapping/translations.md +++ b/docs/mapping/translations.md @@ -187,7 +187,7 @@ EF.Functions.TrigramsStrictWordSimilarityDistanceInverted(s1, s2) | s1 <-> The below translations are for working with label trees from the PostgreSQL [`ltree`](https://www.postgresql.org/docs/current/ltree.html) extension. Use the type to represent ltree and invoke methods on it in EF Core LINQ queries. > [!NOTE] -> LTree support was introduced in version 6.0 of the provider. +> LTree support was introduced in version 6.0 of the provider, and requires PostgreSQL 13 or later. .NET | SQL ----------------------------------------------------------------- | -------------------- diff --git a/docs/release-notes/6.0.md b/docs/release-notes/6.0.md index af4012f50d..d9972f7ba1 100644 --- a/docs/release-notes/6.0.md +++ b/docs/release-notes/6.0.md @@ -25,7 +25,7 @@ Other date/time improvements include: ### Other new features * The provider is now fully annotated for nullable reference types. -* Support for the PostgreSQL [ltree](https://www.postgresql.org/docs/current/ltree.html) type, which represents labels of data stored in a hierarchical tree-like structure. +* Support for the PostgreSQL [ltree](https://www.postgresql.org/docs/current/ltree.html) type, which represents labels of data stored in a hierarchical tree-like structure. Requires PostgreSQL 13 and above. * Multiple spatial translations have been added for NetTopologySuite ([DistanceKnn, <->](https://github.com/npgsql/efcore.pg/issues/1827), [ST_Force2D](https://github.com/npgsql/efcore.pg/issues/1917), [ST_Distance and ST_DWithin with spheriod](https://github.com/npgsql/efcore.pg/issues/1638)). The full list of issues for this release is [available here](https://github.com/npgsql/efcore.pg/milestone/34?closed=1). From 5fce86ab58b9fad6a98f05fc7419c312a0dda0fe Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Tue, 5 Oct 2021 16:06:25 +0200 Subject: [PATCH 069/207] Tweaks to timestamp release notes --- docs/release-notes/6.0.md | 45 ++++++++++++++++++++++----------------- 1 file changed, 26 insertions(+), 19 deletions(-) diff --git a/docs/release-notes/6.0.md b/docs/release-notes/6.0.md index d9972f7ba1..84f4dad642 100644 --- a/docs/release-notes/6.0.md +++ b/docs/release-notes/6.0.md @@ -8,19 +8,21 @@ Npgsql 6.0 brings some major breaking changes and is not a simple in-place upgra ### Timestamp rationalization and improvements -Support for `timestamp with time zone` and `timestamp without time zone` has been rationalized and simplified, and aligned with PostgreSQL best practices. This involves breaking changes, although a compatibility flag can be used to opt out and revert to the previous behavior. +Support for `timestamp with time zone` and `timestamp without time zone` has been rationalized and simplified, and aligned with PostgreSQL best practices. In particular, the "UTC everywhere" pattern is much better supported via the PostgreSQL `timestamp with time zone` type, which is the recommended way to handle timestamps. * UTC timestamps have been cleanly separated from non-UTC timestamps, aligning with the PostgreSQL types. The former are represented by `timestamp with time zone` and DateTime with Kind UTC, the latter by `timestamp without time zone` and DateTime with Kind Local or Unspecified. It is recommended to use UTC timestamps where possible. * Npgsql no longer performs any implicit timezone conversions when reading or writing any timestamp value - the value in the database is what you get, and the machine timezone no longer plays any role when reading/writing values. * Npgsql no longer supports date/time representations which cannot be fully round-tripped to the database. If it can't be fully stored as-is, you can't write it. * A compatibility switch enables opting out of the new behavior, to maintain backwards compatibility. +This change introduces significant breaking changes (see below), although a compatibility flag can be used to opt out and revert to the previous behavior. + Other date/time improvements include: * Support for the new [.NET DateOnly and TimeOnly types](https://devblogs.microsoft.com/dotnet/date-time-and-time-zone-enhancements-in-net-6/). * Most [DateTimeOffset](https://docs.microsoft.com/dotnet/api/system.datetimeoffset) members and methods are now translated. * Many NodaTime translations have been added for [ZonedDateTime](https://nodatime.org/3.0.x/api/NodaTime.ZonedDateTime.html), [Period](https://nodatime.org/3.0.x/api/NodaTime.Period.html), [DateInterval](https://nodatime.org/3.0.x/api/NodaTime.DateInterval.html) and others. -* PostgreSQL `daterange` is now mapped to NodaTime [DateInterval](https://nodatime.org/3.0.x/api/NodaTime.DateInterval.html), and most methods on it are translated. +* PostgreSQL `daterange` is now mapped to NodaTime [DateInterval](https://nodatime.org/3.0.x/api/NodaTime.DateInterval.html), and most methods on it are translated ([#1998](https://github.com/npgsql/efcore.pg/issues/1998)). ### Other new features @@ -37,10 +39,17 @@ The full list of issues for this release is [available here](https://github.com/ > [!NOTE] > It is possible to opt out of these changes to maintain backwards compatibility, see below. -Note: The below notes will use the PostgreSQL aliases `timestamptz` to refer to `timestamp with time zone`, and `timestamp` to refer to `timestamp without time zone`. Note that `timestamp with time zone` represents a UTC timestamp and does **not** store a timezone in the database. +#### Quick summary + +* Most applications want to store UTC timestamps in the database. To do this, migrate your `timestamp without time zone` columns to `timestamp with time zone` ([see migration notes below](#migrating-columns-from-timestamp-to-timestamptz)), and always use DateTime with Kind=Utc when interacting with Npgsql. +* For the few cases where non-UTC timestamps are desired, add explicit configuration to your properties to be `timestamp without time zone` + +#### Detailed notes -* DateTime properties now map to `timestamptz` by default, instead of to `timestamp`; although storing UTC timestamps is the recommended pattern, this will cause the first migration to change your column type. - * If the intention is to store point-in-time or UTC timestamps, it's recommended to allow the migration to occur (see migration notes below). +The below notes will use the PostgreSQL aliases `timestamptz` to refer to `timestamp with time zone`, and `timestamp` to refer to `timestamp without time zone`. Note that `timestamp with time zone` represents a UTC timestamp and does **not** store a timezone in the database. + +* DateTime properties now map to `timestamptz` by default, instead of to `timestamp`; this follows the recommended practice of storing UTC timestamps by default, but will cause the first migration to change your column type. + * If the intention is to store point-in-time or UTC timestamps, it's recommended to allow the migration to occur ([see migration notes below](#migrating-columns-from-timestamp-to-timestamptz)). * If the column really should store non-UTC timestamps (local or unspecified), [explicitly set the column type back to `timestamp`](https://docs.microsoft.com/ef/core/modeling/entity-properties#column-data-types). This is usually discouraged, but can be a temporary solution before transitioning to `timestamptz`. * It is no longer possible to write DateTime with Kinds Local or Unspecified to `timestamptz` properties (which are the default for DateTime). Previously, Npgsql allowed writing those, performing timezone conversions from local to UTC. To write to `timestamptz`, provide a UTC DateTime. Similarly, it is no longer possible to write DateTime with Kind UTC to a `timestamp` column. * `timestamptz` values are now read back as DateTime with Kind=UTC, without any conversions; these were previously returned as local DateTime, converted to the local machine's timezone. When reading `timestamptz` values as [DateTimeOffset](https://docs.microsoft.com/dotnet/api/system.datetimeoffset), UTC values (offset 0) are always returned. @@ -50,21 +59,11 @@ See the [Npgsql ADO.NET docs](/doc/release-notes/5.0.html) for additional lower- #### NodaTime changes -* Properties with type [Instant](https://nodatime.org/3.0.x/api/NodaTime.Instant.html) are now mapped to `timestamptz` columns, and not to `timestamp`, since they represent a universally agreed-upon point in time. Although storing UTC timestamps is the recommended pattern, this will cause the first migration to change your column type. - * If the intention is to store point-in-time or UTC timestamps, it's recommended to allow the migration to occur (see migration notes below). +* Properties with type [Instant](https://nodatime.org/3.0.x/api/NodaTime.Instant.html) are now mapped to `timestamptz` columns, and not to `timestamp`, since they represent a universally agreed-upon point in time. This follows the recommended practice, but will cause the first migration to change your column type. + * If the intention is to store point-in-time or UTC timestamps, it's recommended to allow the migration to occur ([see migration notes below](#migrating-columns-from-timestamp-to-timestamptz)). * If the column really should store non-UTC timestamps (local or unspecified), change the property's type to [LocalDateTime](https://nodatime.org/3.0.x/api/NodaTime.LocalDateTime.html) instead; this will maintain the mapping to `timestamp`. This is usually discouraged, but can be a temporary solution before transitioning to `timestamptz`. * When reading `timestamptz` as [ZonedDateTime](https://nodatime.org/3.0.x/api/NodaTime.ZonedDateTime.html) or [OffsetDateTime](https://nodatime.org/3.0.x/api/NodaTime.OffsetDateTime.html), UTC values are always returned. Previously, local values based on the PostgreSQL `TimeZone` parameter were returned. -#### Opting out of the new timestamp mapping logic - -The changes described above are far-reaching, and may break applications in various ways. You can upgrade to version 6.0 but opt out of the new mapping by enabling the `Npgsql.EnableLegacyTimestampBehavior` [AppContext switch](https://docs.microsoft.com/en-us/dotnet/api/system.appcontext?view=net-5.0): - -To revert to the legacy timestamp behavior, add the following at the start of your application, before any EF Core operations are invoked: - -```c# -AppContext.SetSwitch("Npgsql.EnableLegacyTimestampBehavior", true); -``` - #### Migrating columns from timestamp to timestamptz As a result of the above changes, the first migration created after upgrading to 6.0 will alter the columns for all DateTime and Instant properties from `timestamp` to `timestamptz`. If these columns are meant to store point-in-time or UTC timestamps (the recommended practice), then it's best to let this migration proceed; but care must be taken. @@ -83,7 +82,7 @@ Results in: 2020-01-01 12:00:00 | timestamp without time zone ``` -The migration generated by version 6.0 will cause the following SQL to be executed: +The migration generated by version 6.0 will cause the following SQL to be generated: ```sql ALTER TABLE "Blogs" ALTER COLUMN "CreatedOn" TYPE timestamp with time zone; @@ -97,7 +96,7 @@ When converting the `timestamp without time zone` column to `timestamp with time 2020-01-01 12:00:00+02 | timestamp with time zone ``` -This means that your new `timestamptz` column now contains 10:00 UTC, which is probably not what you want: if the original values were in fact UTC values, you need them to be preserved as-is, with only the column type changing. To do this, edit your migration and add the following to the top of your migration's Up and Down methods: +This means that your new `timestamptz` column now contains 10:00 UTC, which is probably not what you want: if the original values were in fact UTC values, you need them to be preserved as-is, changing only the column type. To do this, edit your migration and add the following to the top of your migration's Up and Down methods: ```c# migrationBuilder.Sql("SET TimeZone='UTC'"); @@ -111,6 +110,14 @@ This will ensure that no time zone conversions will be applied when converting t 2020-01-01 14:00:00+02 | timestamp with time zone ``` +#### Opting out of the new timestamp mapping logic + +The changes described above are far-reaching, and may break applications in various ways. You can upgrade to version 6.0 but opt out of the new mapping by enabling the `Npgsql.EnableLegacyTimestampBehavior` [AppContext switch](https://docs.microsoft.com/en-us/dotnet/api/system.appcontext?view=net-5.0). To do this and revert to the legacy timestamp behavior, add the following at the start of your application, before any Npgsql or EF Core operations are invoked: + +```c# +AppContext.SetSwitch("Npgsql.EnableLegacyTimestampBehavior", true); +``` + ### NodaTime: daterange is scaffolded as DateInterval by default When using NodaTime, a PostgreSQL `daterange` column is scaffolded as a [DateInterval](https://nodatime.org/3.0.x/api/NodaTime.DateInterval.html) property instead of a `NpgsqlRange` property ([#1998](https://github.com/npgsql/efcore.pg/issues/1998)). From 08bbe8f7a5394c2399654469d66c3cb31e6c6084 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Fri, 8 Oct 2021 16:48:04 +0200 Subject: [PATCH 070/207] Remove some evil trailing whitespace --- docs/release-notes/6.0.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/release-notes/6.0.md b/docs/release-notes/6.0.md index 84f4dad642..e5672266e9 100644 --- a/docs/release-notes/6.0.md +++ b/docs/release-notes/6.0.md @@ -8,7 +8,7 @@ Npgsql 6.0 brings some major breaking changes and is not a simple in-place upgra ### Timestamp rationalization and improvements -Support for `timestamp with time zone` and `timestamp without time zone` has been rationalized and simplified, and aligned with PostgreSQL best practices. In particular, the "UTC everywhere" pattern is much better supported via the PostgreSQL `timestamp with time zone` type, which is the recommended way to handle timestamps. +Support for `timestamp with time zone` and `timestamp without time zone` has been rationalized and simplified, and aligned with PostgreSQL best practices. In particular, the "UTC everywhere" pattern is much better supported via the PostgreSQL `timestamp with time zone` type, which is the recommended way to handle timestamps. * UTC timestamps have been cleanly separated from non-UTC timestamps, aligning with the PostgreSQL types. The former are represented by `timestamp with time zone` and DateTime with Kind UTC, the latter by `timestamp without time zone` and DateTime with Kind Local or Unspecified. It is recommended to use UTC timestamps where possible. * Npgsql no longer performs any implicit timezone conversions when reading or writing any timestamp value - the value in the database is what you get, and the machine timezone no longer plays any role when reading/writing values. From 3c20ba646bde5233288027e601cf57797d79a923 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Mon, 11 Oct 2021 22:48:03 +0200 Subject: [PATCH 071/207] Update date/time docs for 6.0 (#127) And generally improve type mapping docs --- docs/release-notes/6.0.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/release-notes/6.0.md b/docs/release-notes/6.0.md index e5672266e9..5f814f726e 100644 --- a/docs/release-notes/6.0.md +++ b/docs/release-notes/6.0.md @@ -8,7 +8,7 @@ Npgsql 6.0 brings some major breaking changes and is not a simple in-place upgra ### Timestamp rationalization and improvements -Support for `timestamp with time zone` and `timestamp without time zone` has been rationalized and simplified, and aligned with PostgreSQL best practices. In particular, the "UTC everywhere" pattern is much better supported via the PostgreSQL `timestamp with time zone` type, which is the recommended way to handle timestamps. +Support for `timestamp with time zone` and `timestamp without time zone` has been rationalized and simplified, and aligned with PostgreSQL best practices. In particular, the "UTC everywhere" pattern is much better supported via the PostgreSQL `timestamp with time zone` type, which is the recommended way to handle timestamps. A detailed explanation is available in [this blog post](https://www.roji.org/postgresql-dotnet-timestamp-mapping), below is a summary of the main improvements. * UTC timestamps have been cleanly separated from non-UTC timestamps, aligning with the PostgreSQL types. The former are represented by `timestamp with time zone` and DateTime with Kind UTC, the latter by `timestamp without time zone` and DateTime with Kind Local or Unspecified. It is recommended to use UTC timestamps where possible. * Npgsql no longer performs any implicit timezone conversions when reading or writing any timestamp value - the value in the database is what you get, and the machine timezone no longer plays any role when reading/writing values. From ff2ca69a7013084d44d71c9ef32fab81a09724f5 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Thu, 14 Oct 2021 17:08:17 +0200 Subject: [PATCH 072/207] Document new 6.0 array translations (#123) See https://github.com/npgsql/efcore.pg/issues/2026 --- docs/mapping/array.md | 37 ++++++++++++++++++++++--------------- docs/release-notes/6.0.md | 1 + 2 files changed, 23 insertions(+), 15 deletions(-) diff --git a/docs/mapping/array.md b/docs/mapping/array.md index db8d19aac4..505eb14e3b 100644 --- a/docs/mapping/array.md +++ b/docs/mapping/array.md @@ -23,18 +23,25 @@ The provider will create `text[]` columns for the above two properties, and will ## Operation translation -The provider can also translate CLR array operations to the corresponding SQL operation; this allows you to efficiently work with arrays by evaluating operations in the database and avoids pulling all the data. The following table lists the range operations that currently get translated. If you run into a missing operation, please open an issue. - -.NET | SQL ---------------------------------------------- | --- -array[1] | [array[1]](https://www.postgresql.org/docs/current/static/arrays.html#ARRAYS-ACCESSING) -array.Length | [cardinality(array)](https://www.postgresql.org/docs/current/static/functions-array.html#ARRAY-FUNCTIONS-TABLE) -array1.SequenceEqual(array2) | [array1 = array2](https://www.postgresql.org/docs/current/static/arrays.html) -array1.Contains(element)) | [element = ANY(array)](https://www.postgresql.org/docs/current/static/functions-comparisons.html#AEN21104) -array.Any() | [cardinality(array) > 0](https://www.postgresql.org/docs/current/static/functions-array.html#ARRAY-FUNCTIONS-TABLE) -array1.Any(i => array2.Contains(i)) | [array1 && array2](https://www.postgresql.org/docs/current/functions-array.html#ARRAY-OPERATORS-TABLE) -array1.All(i => array2.Contains(i)) | [array1 <@ array2](https://www.postgresql.org/docs/current/functions-array.html#ARRAY-OPERATORS-TABLE) -array.Any(s => EF.Functions.Like(string, s)) | [string LIKE ANY (array)](https://www.postgresql.org/docs/current/functions-comparisons.html#id-1.5.8.30.16) -array.Any(s => EF.Functions.ILike(string, s)) | [string ILIKE ANY (array)](https://www.postgresql.org/docs/current/functions-comparisons.html#id-1.5.8.30.16) -array.All(s => EF.Functions.Like(string, s)) | [string LIKE ALL (array)](https://www.postgresql.org/docs/current/functions-comparisons.html#id-1.5.8.30.16) -array.All(s => EF.Functions.ILike(string, s)) | [string ILIKE ALL (array)](https://www.postgresql.org/docs/current/functions-comparisons.html#id-1.5.8.30.16) +The provider can also translate CLR array operations to the corresponding SQL operation; this allows you to efficiently work with arrays by evaluating operations in the database and avoids pulling all the data. The following table lists the range operations that currently get translated; all these translations work both for .NET arrays (`int[]`) and for generic Lists (`List`). If you run into a missing operation, please open an issue. + +.NET | SQL | Notes +--------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- | ---- +array[1] | [array[1]](https://www.postgresql.org/docs/current/static/arrays.html#ARRAYS-ACCESSING) | +array.Length / list.Count | [cardinality(array)](https://www.postgresql.org/docs/current/static/functions-array.html#ARRAY-FUNCTIONS-TABLE) | +array1 == array2 | [array1 = array2](https://www.postgresql.org/docs/current/static/arrays.html) | +array1.SequenceEqual(array2) | [array1 = array2](https://www.postgresql.org/docs/current/static/arrays.html) | +arrayNonColumn.Contains(element)) | [element = ANY(arrayNonColumn)](https://www.postgresql.org/docs/current/static/functions-comparisons.html#AEN21104) | Can use regular index +arrayColumn.Contains(element) | [arrayColumn @> ARRAY\[element\]](https://www.postgresql.org/docs/current/functions-array.html#ARRAY-OPERATORS-TABLE) | Can use GIN index +array.Append(element) | [array_append(array, element)](https://www.postgresql.org/docs/current/functions-array.html#ARRAY-FUNCTIONS-TABLE) | Added in 6.0 +array1.Concat(array2) | [array_cat(array1, array2)](https://www.postgresql.org/docs/current/functions-array.html#ARRAY-FUNCTIONS-TABLE) | Added in 6.0 +array.IndexOf(element) | [array_position(array, element) - 1](https://www.postgresql.org/docs/current/functions-array.html#ARRAY-FUNCTIONS-TABLE) | Added in 6.0 +array.IndexOf(element, startIndex) | [array_position(array, element, startIndex + 1) - 1](https://www.postgresql.org/docs/current/functions-array.html#ARRAY-FUNCTIONS-TABLE) | Added in 6.0 +String.Join(separator, array) | [array_to_string(array, separator, '')](https://www.postgresql.org/docs/current/functions-array.html#ARRAY-FUNCTIONS-TABLE) | Added in 6.0 +array.Any() | [cardinality(array) > 0](https://www.postgresql.org/docs/current/static/functions-array.html#ARRAY-FUNCTIONS-TABLE) | +array1.Any(i => array2.Contains(i)) | [array1 && array2](https://www.postgresql.org/docs/current/functions-array.html#ARRAY-OPERATORS-TABLE) | +array1.All(i => array2.Contains(i)) | [array1 <@ array2](https://www.postgresql.org/docs/current/functions-array.html#ARRAY-OPERATORS-TABLE) | +array.Any(s => EF.Functions.Like(string, s)) | [string LIKE ANY (array)](https://www.postgresql.org/docs/current/functions-comparisons.html#id-1.5.8.30.16) | +array.Any(s => EF.Functions.ILike(string, s)) | [string ILIKE ANY (array)](https://www.postgresql.org/docs/current/functions-comparisons.html#id-1.5.8.30.16) | +array.All(s => EF.Functions.Like(string, s)) | [string LIKE ALL (array)](https://www.postgresql.org/docs/current/functions-comparisons.html#id-1.5.8.30.16) | +array.All(s => EF.Functions.ILike(string, s)) | [string ILIKE ALL (array)](https://www.postgresql.org/docs/current/functions-comparisons.html#id-1.5.8.30.16) | diff --git a/docs/release-notes/6.0.md b/docs/release-notes/6.0.md index 5f814f726e..1a526e11d4 100644 --- a/docs/release-notes/6.0.md +++ b/docs/release-notes/6.0.md @@ -29,6 +29,7 @@ Other date/time improvements include: * The provider is now fully annotated for nullable reference types. * Support for the PostgreSQL [ltree](https://www.postgresql.org/docs/current/ltree.html) type, which represents labels of data stored in a hierarchical tree-like structure. Requires PostgreSQL 13 and above. * Multiple spatial translations have been added for NetTopologySuite ([DistanceKnn, <->](https://github.com/npgsql/efcore.pg/issues/1827), [ST_Force2D](https://github.com/npgsql/efcore.pg/issues/1917), [ST_Distance and ST_DWithin with spheriod](https://github.com/npgsql/efcore.pg/issues/1638)). +* More translations and better type inference for arrays ([#2026](https://github.com/npgsql/efcore.pg/issues/2026)). The full list of issues for this release is [available here](https://github.com/npgsql/efcore.pg/milestone/34?closed=1). From b3aab90dc8e6f3cb722849813ba9d6ff2b0c506e Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Thu, 14 Oct 2021 17:16:12 +0200 Subject: [PATCH 073/207] Add documentation on multiranges (#120) And patch up some range stuff too --- docs/mapping/range.md | 41 ++++++++++++++++++++++++++++++++------- docs/release-notes/6.0.md | 1 + 2 files changed, 35 insertions(+), 7 deletions(-) diff --git a/docs/mapping/range.md b/docs/mapping/range.md index 1c8ae90b5f..fdaae37036 100644 --- a/docs/mapping/range.md +++ b/docs/mapping/range.md @@ -1,8 +1,10 @@ -# Range Type Mapping +# Ranges and Multiranges PostgreSQL has the unique feature of supporting [*range data types*](https://www.postgresql.org/docs/current/static/rangetypes.html). Ranges represent a range of numbers, dates or other data types, and allow you to easily query ranges which contain a value, perform set operations (e.g. query ranges which contain other ranges), and other similar operations. The range operations supported by PostgreSQL are listed [in this page](https://www.postgresql.org/docs/current/static/functions-range.html). The Npgsql EF Core provider allows you to seamlessly map PostgreSQL ranges, and even perform operations on them that get translated to SQL for server evaluation. -## Mapping ranges +In addition, PostgreSQL 14 introduced *multiranges*, which are basically sorted arrays of non-overlapping ranges with set-theoretic operations defined over them. Most range operators also work on multiranges, and they have a few functions of their own. Multirange support in the EF Core provider was introduced in version 6.0.0. + +## Ranges Npgsql maps PostgreSQL ranges to the generic CLR type `NpgsqlRange`: @@ -19,9 +21,6 @@ This will create a column of type `daterange` in your database. You can similarl ## User-defined ranges -> [!NOTE] -> This feature was introduced in version 2.2 - PostgreSQL comes with 6 built-in ranges: `int4range`, `int8range`, `numrange`, `tsrange`, `tstzrange`, `daterange`; these can be used simply by adding the appropriate `NpgsqlRange` property in your entities as shown above. You can also define your own range types over arbitrary types, and use those in EF Core as well. To make the EF Core type mapper aware of your user-defined range, call the `MapRange()` method in your context's `OnConfiguring()` method as follows: @@ -44,6 +43,22 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) This will cause the appropriate [`CREATE TYPE ... AS RANGE`](https://www.postgresql.org/docs/current/static/sql-createtype.html) statement to be generated in your migrations, ensuring that your range is created and ready for use. Note that `HasPostgresRange()` supports additional parameters as supported by PostgreSQL `CREATE TYPE`. +## Multiranges + +> [!NOTE] +> This feature was introduced in version 6.0 + +Npgsql maps arrays or lists of `NpgsqlRange` to PostgreSQL multiranges: + +```c# +public class Store +{ + public int Id { get; set; } + public string Name { get; set; } + public NpgsqlRange[] OpeningTimes { get; set; } +} +``` + ## Operation translation Ranges can be queried via extensions methods on `NpgsqlRange`: @@ -54,11 +69,21 @@ var events = context.Events.Where(p => p.Duration.Contains(someDate)); This will translate to an SQL operation using the PostgreSQL `@>` operator, evaluating at the server and saving you from transferring the entire `Events` table to the client. Note that you can (and probably should) create indexes to make this operation more efficient, see the PostgreSQL docs for more info. -The following table lists the range operations that currently get translated. If you run into a missing operation, please open an issue. +The following table lists the range operations that currently get translated. Most operations work on both ranges and multiranges (starting with version 6.0.0); the multirange version is omitted for brevity. + +If you run into a missing operation, please open an issue. .NET | SQL --------------------------------------|----- -range.Contains(i) | [range @> 3](https://www.postgresql.org/docs/current/static/functions-range.html#RANGE-OPERATORS-TABLE) +range.LowerBound | [lower(range)](https://www.postgresql.org/docs/current/functions-range.html#RANGE-FUNCTIONS-TABLE) +range.UpperBound | [upper(range)](https://www.postgresql.org/docs/current/functions-range.html#RANGE-FUNCTIONS-TABLE) +range.LowerBoundIsInclusive | [lower_inc(range)](https://www.postgresql.org/docs/current/functions-range.html#RANGE-FUNCTIONS-TABLE) +range.UpperBoundIsInclusive | [upper_inc(range)](https://www.postgresql.org/docs/current/functions-range.html#RANGE-FUNCTIONS-TABLE) +range.LowerBoundIsInfinite | [lower_inf(range)](https://www.postgresql.org/docs/current/functions-range.html#RANGE-FUNCTIONS-TABLE) +range.UpperBoundIsInfinite | [upper_inf(range)](https://www.postgresql.org/docs/current/functions-range.html#RANGE-FUNCTIONS-TABLE) +range.IsEmpty | [isempty(range)](https://www.postgresql.org/docs/current/functions-range.html#RANGE-FUNCTIONS-TABLE) +multirange.Any() | [NOT is_empty(multirange)](https://www.postgresql.org/docs/current/functions-range.html#MULTIRANGE-FUNCTIONS-TABLE) +range.Contains(i) | [range @> i](https://www.postgresql.org/docs/current/static/functions-range.html#RANGE-OPERATORS-TABLE) range1.Contains(range2) | [range @> range2](https://www.postgresql.org/docs/current/static/functions-range.html#RANGE-OPERATORS-TABLE) range1.ContainedBy(range2) | [range1 <@ range2](https://www.postgresql.org/docs/current/static/functions-range.html#RANGE-OPERATORS-TABLE) range1.Overlaps(range2) | [range1 && range2](https://www.postgresql.org/docs/current/static/functions-range.html#RANGE-OPERATORS-TABLE) @@ -70,3 +95,5 @@ range1.IsAdjacentTo(range2) | [range1 -\|- range2](https://www.postgre range1.Union(range2) | [range1 + range2](https://www.postgresql.org/docs/current/static/functions-range.html#RANGE-OPERATORS-TABLE) range1.Intersect(range2) | [range1 * range2](https://www.postgresql.org/docs/current/static/functions-range.html#RANGE-OPERATORS-TABLE) range1.Except(range2) | [range1 - range2](https://www.postgresql.org/docs/current/static/functions-range.html#RANGE-OPERATORS-TABLE) +range1.Merge(range2) | [range_merge(range1, range2)](https://www.postgresql.org/docs/current/functions-range.html#RANGE-FUNCTIONS-TABLE) +multirange.Merge() | [range_merge(multirange)](https://www.postgresql.org/docs/current/functions-range.html#MULTIRANGE-FUNCTIONS-TABLE) diff --git a/docs/release-notes/6.0.md b/docs/release-notes/6.0.md index 1a526e11d4..a3c0c40fed 100644 --- a/docs/release-notes/6.0.md +++ b/docs/release-notes/6.0.md @@ -27,6 +27,7 @@ Other date/time improvements include: ### Other new features * The provider is now fully annotated for nullable reference types. +* Full support for the upcoming PostgreSQL 14 [multirange type](https://www.postgresql.org/docs/14/rangetypes.html), mapped to arrays or lists of `NpgsqlRange` ([#1963](https://github.com/npgsql/efcore.pg/issues/1963)). Includes translation of all major operators and functions, [see the updated docs](../mapping/range.md). * Support for the PostgreSQL [ltree](https://www.postgresql.org/docs/current/ltree.html) type, which represents labels of data stored in a hierarchical tree-like structure. Requires PostgreSQL 13 and above. * Multiple spatial translations have been added for NetTopologySuite ([DistanceKnn, <->](https://github.com/npgsql/efcore.pg/issues/1827), [ST_Force2D](https://github.com/npgsql/efcore.pg/issues/1917), [ST_Distance and ST_DWithin with spheriod](https://github.com/npgsql/efcore.pg/issues/1638)). * More translations and better type inference for arrays ([#2026](https://github.com/npgsql/efcore.pg/issues/2026)). From 3f795a72ce82c3af7bcf812a1c947662b1d86e59 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Fri, 15 Oct 2021 18:41:09 +0200 Subject: [PATCH 074/207] Notes on date/time infinity conversions (#129) --- docs/release-notes/6.0.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/docs/release-notes/6.0.md b/docs/release-notes/6.0.md index a3c0c40fed..bed1153abe 100644 --- a/docs/release-notes/6.0.md +++ b/docs/release-notes/6.0.md @@ -124,6 +124,16 @@ AppContext.SetSwitch("Npgsql.EnableLegacyTimestampBehavior", true); When using NodaTime, a PostgreSQL `daterange` column is scaffolded as a [DateInterval](https://nodatime.org/3.0.x/api/NodaTime.DateInterval.html) property instead of a `NpgsqlRange` property ([#1998](https://github.com/npgsql/efcore.pg/issues/1998)). +### Date/time min/max values are now converted to PostgreSQL infinity values by default + +PostgreSQL has special `infinity` and `-infinity` values for timestamps and dates, which are later and earlier than other value. Npgsql has supported mapping `DateTime.MaxValue` and `MinValue` to these infinity values via an `Convert Infinity DateTime` connection string parameter, which was disabled by default. This behavior is now on by default, since `DateTime.MaxValue` and `MinValue` are very rarely used as actual timestamps/dates, and the `Convert Infinity DateTime` parameter has been removed. To disable infinity conversions, add the following at the start of your application: + +```c# +AppContext.SetSwitch("Npgsql.DisableDateTimeInfinityConversions", true); +``` + +[See the date/time documentation](/doc/types/datetime.html#infinity-values) for more details. + ### Value converters for array/list properties need to use a special new API Previously, it was possible to configure value converters for array/list properties with the general EF Core API: From fe7ce89db3274191f67d605354a5015415958964 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Thu, 21 Oct 2021 13:19:46 +0200 Subject: [PATCH 075/207] Document new timezone conversion translations (#134) See https://github.com/npgsql/efcore.pg/pull/2052 --- docs/mapping/nodatime.md | 1 + docs/mapping/translations.md | 72 ++++++++++++++++++------------------ 2 files changed, 38 insertions(+), 35 deletions(-) diff --git a/docs/mapping/nodatime.md b/docs/mapping/nodatime.md index e90f8dfcc2..4127e9d549 100644 --- a/docs/mapping/nodatime.md +++ b/docs/mapping/nodatime.md @@ -91,5 +91,6 @@ DateInterval.Contains(DateInterval) | [daterange @> daterang DateInterval.Intersection(DateInterval) | [daterange * daterange](https://www.postgresql.org/docs/current/functions-range.html) | Added in 6.0 DateInterval.Union(DateInterval) | [daterange + daterange](https://www.postgresql.org/docs/current/functions-range.html) | Added in 6.0 Instant.InUtc | No PG operation (.NET-side conversion from Instant to ZonedDateTime only) | Added in 6.0 +Instant.ToDateTimeUtc | No PG operation (.NET-side conversion from Instant to UTC DateTime only) | Added in 6.0 In addition to the above, most arithmetic operators are also translated (e.g. LocalDate + Period). diff --git a/docs/mapping/translations.md b/docs/mapping/translations.md index 1ffb454f18..0311e89320 100644 --- a/docs/mapping/translations.md +++ b/docs/mapping/translations.md @@ -18,41 +18,43 @@ bytes1.SequenceEqual(bytes2) | @bytes = @second | Added in 5.0 > [!NOTE] > Since version 6.0, many of the below DateTime translations are also supported on DateTimeOffset. -.NET | SQL | Notes ------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- | -------- -DateTime.UtcNow (6.0+) | [now()](https://www.postgresql.org/docs/current/functions-datetime.html) | See 6.0 release notes -DateTime.Now (6.0+) | [now()::timestamp](https://www.postgresql.org/docs/current/functions-datetime.html) | See 6.0 release notes -DateTime.Today (6.0+) | [date_trunc('day', now()::timestamp)](https://www.postgresql.org/docs/current/functions-datetime.html) | See 6.0 release notes -DateTime.UtcNow (legacy) | [now() AT TIME ZONE 'UTC'](https://www.postgresql.org/docs/current/functions-datetime.html) | See 6.0 release notes -DateTime.Now (legacy) | [now()](https://www.postgresql.org/docs/current/functions-datetime.html) | See 6.0 release notes -DateTime.Today (legacy) | [date_trunc('day', now())](https://www.postgresql.org/docs/current/functions-datetime.html) | See 6.0 release notes -dateTime.AddDays(1) | [dateTime + INTERVAL '1 days'](https://www.postgresql.org/docs/current/functions-datetime.html#OPERATORS-DATETIME-TABLE) | -dateTime.AddHours(value) | [dateTime + INTERVAL '1 hours'](https://www.postgresql.org/docs/current/functions-datetime.html#OPERATORS-DATETIME-TABLE) | -dateTime.AddMinutes(1) | [dateTime + INTERVAL '1 minutes'](https://www.postgresql.org/docs/current/functions-datetime.html#OPERATORS-DATETIME-TABLE) | -dateTime.AddMonths(1) | [dateTime + INTERVAL '1 months'](https://www.postgresql.org/docs/current/functions-datetime.html#OPERATORS-DATETIME-TABLE) | -dateTime.AddSeconds(1) | [dateTime + INTERVAL '1 seconds'](https://www.postgresql.org/docs/current/functions-datetime.html#OPERATORS-DATETIME-TABLE) | -dateTime.AddYears(1) | [dateTime + INTERVAL '1 years'](https://www.postgresql.org/docs/current/functions-datetime.html#OPERATORS-DATETIME-TABLE) | -dateTime.Date | [date_trunc('day', dateTime)](https://www.postgresql.org/docs/current/functions-datetime.html) | -dateTime.Day | [date_part('day', dateTime)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | -dateTime.DayOfWeek | [floor(date_part('dow', dateTime))::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | -dateTime.DayOfYear | [date_part('doy', dateTime)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | -dateTime.Hour | [date_part('hour', dateTime)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | -dateTime.Minute | [date_part('minute', dateTime)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | -dateTime.Month | [date_part('month', dateTime)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | -dateTime.Second | [date_part('second', dateTime)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | -dateTime.Year | [date_part('year', dateTime)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | -dateTime.ToUniversalTime | [dateTime::timestamptz](https://www.postgresql.org/docs/current/datatype-datetime.html#id-1.5.7.13.18.7) | Added in 6.0 -dateTime.ToLocalTime | [dateTime::timestamp](https://www.postgresql.org/docs/current/datatype-datetime.html#id-1.5.7.13.18.7) | Added in 6.0 -timeSpan.Days | [floor(date_part('day', timeSpan))::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | -timeSpan.Hours | [floor(date_part('hour', timeSpan))::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | -timeSpan.Minutes | [floor(date_part('minute', timeSpan))::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | -timeSpan.Seconds | [floor(date_part('second', timeSpan))::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | -timeSpan.Milliseconds | [floor(date_part('millisecond', timeSpan))::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | -timeSpan.Milliseconds | [floor(date_part('millisecond', timeSpan))::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | -dateTime1 - dateTime2 | [dateTime1 - dateTime2](https://www.postgresql.org/docs/current/functions-datetime.html#OPERATORS-DATETIME-TABLE) | -new DateTime(year, month, day) | [make_date(year, month, day)](https://www.postgresql.org/docs/current/functions-datetime.html) | -new DateTime(y, m, d, h, m, s) | [make_timestamp(y, m, d, h, m, s)](https://www.postgresql.org/docs/current/functions-datetime.html) | -new DateTime(y, m, d, h, m, s, kind) | [make_timestamp or make_timestamptz](https://www.postgresql.org/docs/current/functions-datetime.html), based on `king` | Added in 6.0 +.NET | SQL | Notes +----------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- | -------- +DateTime.UtcNow (6.0+) | [now()](https://www.postgresql.org/docs/current/functions-datetime.html) | See 6.0 release notes +DateTime.Now (6.0+) | [now()::timestamp](https://www.postgresql.org/docs/current/functions-datetime.html) | See 6.0 release notes +DateTime.Today (6.0+) | [date_trunc('day', now()::timestamp)](https://www.postgresql.org/docs/current/functions-datetime.html) | See 6.0 release notes +DateTime.UtcNow (legacy) | [now() AT TIME ZONE 'UTC'](https://www.postgresql.org/docs/current/functions-datetime.html) | See 6.0 release notes +DateTime.Now (legacy) | [now()](https://www.postgresql.org/docs/current/functions-datetime.html) | See 6.0 release notes +DateTime.Today (legacy) | [date_trunc('day', now())](https://www.postgresql.org/docs/current/functions-datetime.html) | See 6.0 release notes +dateTime.AddDays(1) | [dateTime + INTERVAL '1 days'](https://www.postgresql.org/docs/current/functions-datetime.html#OPERATORS-DATETIME-TABLE) | +dateTime.AddHours(value) | [dateTime + INTERVAL '1 hours'](https://www.postgresql.org/docs/current/functions-datetime.html#OPERATORS-DATETIME-TABLE) | +dateTime.AddMinutes(1) | [dateTime + INTERVAL '1 minutes'](https://www.postgresql.org/docs/current/functions-datetime.html#OPERATORS-DATETIME-TABLE) | +dateTime.AddMonths(1) | [dateTime + INTERVAL '1 months'](https://www.postgresql.org/docs/current/functions-datetime.html#OPERATORS-DATETIME-TABLE) | +dateTime.AddSeconds(1) | [dateTime + INTERVAL '1 seconds'](https://www.postgresql.org/docs/current/functions-datetime.html#OPERATORS-DATETIME-TABLE) | +dateTime.AddYears(1) | [dateTime + INTERVAL '1 years'](https://www.postgresql.org/docs/current/functions-datetime.html#OPERATORS-DATETIME-TABLE) | +dateTime.Date | [date_trunc('day', dateTime)](https://www.postgresql.org/docs/current/functions-datetime.html) | +dateTime.Day | [date_part('day', dateTime)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | +dateTime.DayOfWeek | [floor(date_part('dow', dateTime))::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | +dateTime.DayOfYear | [date_part('doy', dateTime)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | +dateTime.Hour | [date_part('hour', dateTime)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | +dateTime.Minute | [date_part('minute', dateTime)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | +dateTime.Month | [date_part('month', dateTime)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | +dateTime.Second | [date_part('second', dateTime)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | +dateTime.Year | [date_part('year', dateTime)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | +dateTime.ToUniversalTime | [dateTime::timestamptz](https://www.postgresql.org/docs/current/datatype-datetime.html#id-1.5.7.13.18.7) | Added in 6.0 +dateTime.ToLocalTime | [dateTime::timestamp](https://www.postgresql.org/docs/current/datatype-datetime.html#id-1.5.7.13.18.7) | Added in 6.0 +timeSpan.Days | [floor(date_part('day', timeSpan))::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | +timeSpan.Hours | [floor(date_part('hour', timeSpan))::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | +timeSpan.Minutes | [floor(date_part('minute', timeSpan))::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | +timeSpan.Seconds | [floor(date_part('second', timeSpan))::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | +timeSpan.Milliseconds | [floor(date_part('millisecond', timeSpan))::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | +timeSpan.Milliseconds | [floor(date_part('millisecond', timeSpan))::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | +dateTime1 - dateTime2 | [dateTime1 - dateTime2](https://www.postgresql.org/docs/current/functions-datetime.html#OPERATORS-DATETIME-TABLE) | +TimeZoneInfo.ConvertTimeBySystemTimeZoneId(utcDateTime, timezone) | [utcDateTime AT TIME ZONE timezone](https://www.postgresql.org/docs/current/functions-datetime.html#FUNCTIONS-DATETIME-ZONECONVERT) | Added in 6.0, only for timestamptz columns +TimeZoneInfo.ConvertTimeToUtc(nonUtcDateTime) | [nonUtcDateTime AT TIME ZONE timezone](https://www.postgresql.org/docs/current/functions-datetime.html#FUNCTIONS-DATETIME-ZONECONVERT) | Added in 6.0, only for timestamp columns +new DateTime(year, month, day) | [make_date(year, month, day)](https://www.postgresql.org/docs/current/functions-datetime.html) | +new DateTime(y, m, d, h, m, s) | [make_timestamp(y, m, d, h, m, s)](https://www.postgresql.org/docs/current/functions-datetime.html) | +new DateTime(y, m, d, h, m, s, kind) | [make_timestamp or make_timestamptz](https://www.postgresql.org/docs/current/functions-datetime.html), based on `king` | Added in 6.0 > [!NOTE] > See also Npgsql's [NodaTime support](/efcore/mapping/nodatime.html). From f858807c5d66760229682cb4c0a47c73e2b106b4 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Fri, 22 Oct 2021 02:46:13 +0200 Subject: [PATCH 076/207] Document NodaTime timezone conversion translations (#135) See https://github.com/npgsql/efcore.pg/pull/2055 --- docs/mapping/nodatime.md | 83 +++++++++++++++++++++------------------- 1 file changed, 43 insertions(+), 40 deletions(-) diff --git a/docs/mapping/nodatime.md b/docs/mapping/nodatime.md index 4127e9d549..64b62d7aae 100644 --- a/docs/mapping/nodatime.md +++ b/docs/mapping/nodatime.md @@ -52,45 +52,48 @@ Following is the list of supported NodaTime translations; If an operation you ne > [!NOTE] > Most translations on ZonedDateTime and Period were added in version 6.0 -.NET | SQL | Notes -------------------------------------------------------- |------------------------------------------------------------------------- | --- -SystemClock.Instance.GetCurrentInstant() | [now()](https://www.postgresql.org/docs/current/functions-datetime.html) -LocalDateTime.Date | [date_trunc('day', timestamp)](https://www.postgresql.org/docs/current/functions-datetime.html) -LocalDateTime.Second (also LocalTime, ZonedDateTime) | [date_part('second', timestamp)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) -LocalDateTime.Minute (also LocalTime, ZonedDateTime) | [date_part('minute', timestamp)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) -LocalDateTime.Hour (also LocalTime, ZonedDateTime) | [date_part('hour', timestamp)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) -LocalDateTime.Day, (also LocalDate, ZonedDateTime) | [date_part('day', timestamp)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) -LocalDateTime.Month (also LocalDate, ZonedDateTime) | [date_part('month', timestamp)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) -LocalDateTime.Year (also LocalDate, ZonedDateTime) | [date_part('year', timestamp)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) -LocalDateTime.DayOfWeek (also LocalDate, ZonedDateTime) | [floor(date_part('dow', timestamp))::INT](https://www.postgresql.org/docs/current/functions-datetime.html) -LocalDateTime.DayOfYear (also LocalDate, ZonedDateTime) | [date_part('doy', timestamp)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) -Period.Seconds (also Duration) | [date_part('second', interval)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) -Period.Minutes (also Duration) | [date_part('minute', interval)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) -Period.Hours (also Duration) | [date_part('hour', interval)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) -Period.Days (also Duration) | [date_part('day', interval)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) -Period.Months | [date_part('month', interval)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) -Period.Years | [date_part('year', interval)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) -Period.FromSeconds | [make_interval(seconds => int)](https://www.postgresql.org/docs/current/functions-datetime.html) -Period.FromMinutes | [make_interval(minutes => int)](https://www.postgresql.org/docs/current/functions-datetime.html) -Period.FromHours | [make_interval(hours => int)](https://www.postgresql.org/docs/current/functions-datetime.html) -Period.FromDays | [make_interval(days => int)](https://www.postgresql.org/docs/current/functions-datetime.html) -Period.FromWeeks | [make_interval(weeks => int)](https://www.postgresql.org/docs/current/functions-datetime.html) -Period.FromMonths | [make_interval(months => int)](https://www.postgresql.org/docs/current/functions-datetime.html) -Period.FromYears | [make_interval(years => int)](https://www.postgresql.org/docs/current/functions-datetime.html) -Duration.TotalMilliseconds | [date_part('epoch', interval) / 0.001](https://www.postgresql.org/docs/current/functions-datetime.html) -Duration.TotalSeconds | [date_part('epoch', interval)](https://www.postgresql.org/docs/current/functions-datetime.html) -Duration.TotalMinutes | [date_part('epoch', interval) / 60.0](https://www.postgresql.org/docs/current/functions-datetime.html) -Duration.TotalDays | [date_part('epoch', interval) / 86400.0](https://www.postgresql.org/docs/current/functions-datetime.html) -Duration.TotalHours | [date_part('epoch', interval) / 3600.0](https://www.postgresql.org/docs/current/functions-datetime.html) -ZonedDateTime.LocalDateTime | [timestamptz AT TIME ZONE 'UTC'](https://www.postgresql.org/docs/current/functions-datetime.html#FUNCTIONS-DATETIME-ZONECONVERT) | Added in 6.0 -DateInterval.Length | [upper(daterange) - lower(daterange)](https://www.postgresql.org/docs/current/functions-range.html) | Added in 6.0 -DateInterval.Start | [lower(daterange)](https://www.postgresql.org/docs/current/functions-range.html) | Added in 6.0 -DateInterval.End | [upper(daterange) - INTERVAL 'P1D'](https://www.postgresql.org/docs/current/functions-range.html) | Added in 6.0 -DateInterval.Contains(LocalDate) | [daterange @> date](https://www.postgresql.org/docs/current/functions-range.html) | Added in 6.0 -DateInterval.Contains(DateInterval) | [daterange @> daterange](https://www.postgresql.org/docs/current/functions-range.html) | Added in 6.0 -DateInterval.Intersection(DateInterval) | [daterange * daterange](https://www.postgresql.org/docs/current/functions-range.html) | Added in 6.0 -DateInterval.Union(DateInterval) | [daterange + daterange](https://www.postgresql.org/docs/current/functions-range.html) | Added in 6.0 -Instant.InUtc | No PG operation (.NET-side conversion from Instant to ZonedDateTime only) | Added in 6.0 -Instant.ToDateTimeUtc | No PG operation (.NET-side conversion from Instant to UTC DateTime only) | Added in 6.0 +.NET | SQL | Notes +-------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ | ----------- +SystemClock.Instance.GetCurrentInstant() | [now()](https://www.postgresql.org/docs/current/functions-datetime.html) | +LocalDateTime.Date | [date_trunc('day', timestamp)](https://www.postgresql.org/docs/current/functions-datetime.html) | +LocalDateTime.Second (also LocalTime, ZonedDateTime) | [date_part('second', timestamp)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | +LocalDateTime.Minute (also LocalTime, ZonedDateTime) | [date_part('minute', timestamp)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | +LocalDateTime.Hour (also LocalTime, ZonedDateTime) | [date_part('hour', timestamp)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | +LocalDateTime.Day, (also LocalDate, ZonedDateTime) | [date_part('day', timestamp)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | +LocalDateTime.Month (also LocalDate, ZonedDateTime) | [date_part('month', timestamp)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | +LocalDateTime.Year (also LocalDate, ZonedDateTime) | [date_part('year', timestamp)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | +LocalDateTime.DayOfWeek (also LocalDate, ZonedDateTime) | [floor(date_part('dow', timestamp))::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | +LocalDateTime.DayOfYear (also LocalDate, ZonedDateTime) | [date_part('doy', timestamp)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | +Period.Seconds (also Duration) | [date_part('second', interval)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | +Period.Minutes (also Duration) | [date_part('minute', interval)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | +Period.Hours (also Duration) | [date_part('hour', interval)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | +Period.Days (also Duration) | [date_part('day', interval)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | +Period.Months | [date_part('month', interval)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | +Period.Years | [date_part('year', interval)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | +Period.FromSeconds | [make_interval(seconds => int)](https://www.postgresql.org/docs/current/functions-datetime.html) | +Period.FromMinutes | [make_interval(minutes => int)](https://www.postgresql.org/docs/current/functions-datetime.html) | +Period.FromHours | [make_interval(hours => int)](https://www.postgresql.org/docs/current/functions-datetime.html) | +Period.FromDays | [make_interval(days => int)](https://www.postgresql.org/docs/current/functions-datetime.html) | +Period.FromWeeks | [make_interval(weeks => int)](https://www.postgresql.org/docs/current/functions-datetime.html) | +Period.FromMonths | [make_interval(months => int)](https://www.postgresql.org/docs/current/functions-datetime.html) | +Period.FromYears | [make_interval(years => int)](https://www.postgresql.org/docs/current/functions-datetime.html) | +Duration.TotalMilliseconds | [date_part('epoch', interval) / 0.001](https://www.postgresql.org/docs/current/functions-datetime.html) | +Duration.TotalSeconds | [date_part('epoch', interval)](https://www.postgresql.org/docs/current/functions-datetime.html) | +Duration.TotalMinutes | [date_part('epoch', interval) / 60.0](https://www.postgresql.org/docs/current/functions-datetime.html) | +Duration.TotalDays | [date_part('epoch', interval) / 86400.0](https://www.postgresql.org/docs/current/functions-datetime.html) | +Duration.TotalHours | [date_part('epoch', interval) / 3600.0](https://www.postgresql.org/docs/current/functions-datetime.html) | +ZonedDateTime.LocalDateTime | [timestamptz AT TIME ZONE 'UTC'](https://www.postgresql.org/docs/current/functions-datetime.html#FUNCTIONS-DATETIME-ZONECONVERT) | Added in 6.0 +DateInterval.Length | [upper(daterange) - lower(daterange)](https://www.postgresql.org/docs/current/functions-range.html) | Added in 6.0 +DateInterval.Start | [lower(daterange)](https://www.postgresql.org/docs/current/functions-range.html) | Added in 6.0 +DateInterval.End | [upper(daterange) - INTERVAL 'P1D'](https://www.postgresql.org/docs/current/functions-range.html) | Added in 6.0 +DateInterval.Contains(LocalDate) | [daterange @> date](https://www.postgresql.org/docs/current/functions-range.html) | Added in 6.0 +DateInterval.Contains(DateInterval) | [daterange @> daterange](https://www.postgresql.org/docs/current/functions-range.html) | Added in 6.0 +DateInterval.Intersection(DateInterval) | [daterange * daterange](https://www.postgresql.org/docs/current/functions-range.html) | Added in 6.0 +DateInterval.Union(DateInterval) | [daterange + daterange](https://www.postgresql.org/docs/current/functions-range.html) | Added in 6.0 +Instant.InZone(DateTimeZoneProviders.Tzdb["Europe/Berlin"]).LocalDateTime | [timestamptz AT TIME ZONE 'Europe/Berlin'](https://www.postgresql.org/docs/current/functions-datetime.html#FUNCTIONS-DATETIME-ZONECONVERT) | Added in 6.0 +LocalDateTime.InZoneLeniently(DateTimeZoneProviders.Tzdb["Europe/Berlin"]).ToInstant() | [timestamp AT TIME ZONE 'Europe/Berlin'](https://www.postgresql.org/docs/current/functions-datetime.html#FUNCTIONS-DATETIME-ZONECONVERT) | Added in 6.0 +ZonedDateTime.ToInstant | No PG operation (.NET-side conversion from ZonedDateTime to Instant only) | Added in 6.0 +Instant.InUtc | No PG operation (.NET-side conversion from Instant to ZonedDateTime only) | Added in 6.0 +Instant.ToDateTimeUtc | No PG operation (.NET-side conversion from Instant to UTC DateTime only) | Added in 6.0 In addition to the above, most arithmetic operators are also translated (e.g. LocalDate + Period). From efd43be9d832e5f559efda0f93d1911cb70ede28 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Sun, 24 Oct 2021 15:56:33 +0200 Subject: [PATCH 077/207] Document full-text search translations (#136) Closes #119 --- docs/mapping/full-text-search.md | 43 ++++++++++++++++++++++++++------ 1 file changed, 35 insertions(+), 8 deletions(-) diff --git a/docs/mapping/full-text-search.md b/docs/mapping/full-text-search.md index f58a1072e2..cea422d835 100644 --- a/docs/mapping/full-text-search.md +++ b/docs/mapping/full-text-search.md @@ -147,18 +147,45 @@ var npgsql = context.Products ## Operation translation -Almost all PostgreSQL full text search functions can be called through LINQ queries. All supported EF Core LINQ methods are defined in extension classes in the `Microsoft.EntityFrameworkCore` namespace, so simply referencing the Npgsql provider will light up these methods. Here is a table showing translations for some operations; if an operation you need is missing, please open an issue to request for it. +Almost all PostgreSQL full text search functions can be called through LINQ queries. All supported EF Core LINQ methods are defined in extension classes in the `Microsoft.EntityFrameworkCore` namespace, so simply referencing the Npgsql provider will light up these methods. The following table lists all supported operations; if an operation you need is missing, please open an issue to request for it. .NET | SQL ----------------------------------------------------------------------------|----- +EF.Functions.ToTsVector(string) | [to_tsvector(string)](https://www.postgresql.org/docs/current/static/textsearch-controls.html#TEXTSEARCH-PARSING-DOCUMENTS) EF.Functions.ToTsVector("english", string) | [to_tsvector('english'::regconfig, string)](https://www.postgresql.org/docs/current/static/textsearch-controls.html#TEXTSEARCH-PARSING-DOCUMENTS) +EF.Functions.ToTsQuery(string)) | [to_tsquery(string)](https://www.postgresql.org/docs/current/static/textsearch-controls.html#TEXTSEARCH-PARSING-QUERIES) +EF.Functions.ToTsQuery("english", string)) | [to_tsquery('english'::regconfig, string)](https://www.postgresql.org/docs/current/static/textsearch-controls.html#TEXTSEARCH-PARSING-QUERIES) +EF.Functions.PlainToTsQuery(string)) | [plainto_tsquery(string)](https://www.postgresql.org/docs/current/static/textsearch-controls.html#TEXTSEARCH-PARSING-QUERIES) +EF.Functions.PlainToTsQuery("english", string)) | [plainto_tsquery('english'::regconfig, string)](https://www.postgresql.org/docs/current/static/textsearch-controls.html#TEXTSEARCH-PARSING-QUERIES) +EF.Functions.PhraseToTsQuery(string)) | [phraseto_tsquery(string)](https://www.postgresql.org/docs/current/static/textsearch-controls.html#TEXTSEARCH-PARSING-QUERIES) +EF.Functions.PhraseToTsQuery("english", string)) | [phraseto_tsquery('english'::regconfig, string)](https://www.postgresql.org/docs/current/static/textsearch-controls.html#TEXTSEARCH-PARSING-QUERIES) +EF.Functions.WebSearchToTsQuery(string)) | [websearch_to_tsquery(string)](https://www.postgresql.org/docs/current/static/textsearch-controls.html#TEXTSEARCH-PARSING-QUERIES) +EF.Functions.WebSearchToTsQuery("english", string)) | [websearch_to_tsquery('english'::regconfig, string)](https://www.postgresql.org/docs/current/static/textsearch-controls.html#TEXTSEARCH-PARSING-QUERIES) +EF.functions.ArrayToTsVector(new[] { "a", "b" }) | [array_to_tsvector(ARRAY['a', 'b'])](https://www.postgresql.org/docs/current/functions-textsearch.html#TEXTSEARCH-FUNCTIONS-TABLE) NpgsqlTsVector.Parse(string)) | [CAST(string AS tsvector)](https://www.postgresql.org/docs/current/static/sql-expressions.html#SQL-SYNTAX-TYPE-CASTS) -EF.Functions.ToTsQuery("english", queryString)) | [to_tsquery('english'::regconfig, queryString)](https://www.postgresql.org/docs/current/static/textsearch-controls.html#TEXTSEARCH-PARSING-QUERIES) -NpgsqlTsQuery.Parse(queryString)) | [CAST(queryString AS tsquery)](https://www.postgresql.org/docs/current/static/sql-expressions.html#SQL-SYNTAX-TYPE-CASTS) -tsVector.Matches(queryString)) | [tsVector @@ queryString](https://www.postgresql.org/docs/current/static/textsearch-intro.html#TEXTSEARCH-MATCHING) -tsVector.Matches(tsQuery) | [tsVector @@ tsQuery](https://www.postgresql.org/docs/current/static/textsearch-controls.html#TEXTSEARCH-PARSING-QUERIES) -tsQuery.ToNegative() | [!! tsQuery](https://www.postgresql.org/docs/current/static/textsearch-features.html#TEXTSEARCH-MANIPULATE-TSQUERY) -tsVector.SetWeight(NpgsqlTsVector.Lexeme.Weight.A)) | [setweight(tsVector, 'A')](https://www.postgresql.org/docs/current/static/textsearch-features.html#TEXTSEARCH-MANIPULATE-TSVECTOR) -tsVector.Rank(tsQuery) | [ts_rank(tsVector, tsQuery)](https://www.postgresql.org/docs/current/textsearch-controls.html#TEXTSEARCH-RANKING) +NpgsqlTsQuery.Parse(string)) | [CAST(queryString AS tsquery)](https://www.postgresql.org/docs/current/static/sql-expressions.html#SQL-SYNTAX-TYPE-CASTS) +tsvector.Matches(string)) | [tsvector @@ string](https://www.postgresql.org/docs/current/static/textsearch-intro.html#TEXTSEARCH-MATCHING) +tsvector.Matches(tsquery) | [tsvector @@ tsquery](https://www.postgresql.org/docs/current/static/textsearch-controls.html#TEXTSEARCH-PARSING-QUERIES) +tsquery1.And(tsquery2) | [tsquery1 && tsquery2](https://www.postgresql.org/docs/current/static/textsearch-features.html#TEXTSEARCH-MANIPULATE-TSQUERY) +tsquery1.Or(tsquery2) | [tsquery1 \|\| tsquery2](https://www.postgresql.org/docs/current/static/textsearch-features.html#TEXTSEARCH-MANIPULATE-TSQUERY) +tsquery.ToNegative() | [!! tsquery](https://www.postgresql.org/docs/current/static/textsearch-features.html#TEXTSEARCH-MANIPULATE-TSQUERY) +tsquery1.Contains(tsquery2) | [tsquery1 @> tsquery2](https://www.postgresql.org/docs/current/static/textsearch-features.html#TEXTSEARCH-MANIPULATE-TSQUERY) +tsquery1.IscontainedIn(tsquery2) | [tsquery1 <@ tsquery2](https://www.postgresql.org/docs/current/static/textsearch-features.html#TEXTSEARCH-MANIPULATE-TSQUERY) +tsquery.GetNodeCount() | [numnode(query)](https://www.postgresql.org/docs/current/static/textsearch-features.html#TEXTSEARCH-MANIPULATE-TSQUERY) +tsquery.GetQueryTree() | [querytree(query)](https://www.postgresql.org/docs/current/static/textsearch-features.html#TEXTSEARCH-MANIPULATE-TSQUERY) +tsquery.GetResultHeadline("a b c") | [ts_headline('a b c', query)](https://www.postgresql.org/docs/current/textsearch-controls.html#TEXTSEARCH-HEADLINE) +tsquery.GetResultHeadline("a b c", "MinWords=1, MaxWords=2") | [ts_headline('a b c', query, 'MinWords=1, MaxWords=2')](https://www.postgresql.org/docs/current/textsearch-controls.html#TEXTSEARCH-HEADLINE) +tsquery.Rewrite(targetQuery, substituteQuery) | [ts_rewrite(to_tsquery(tsquery), to_tsquery(targetQuery), to_tsquery(substituteQuery))](https://www.postgresql.org/docs/current/functions-textsearch.html#TEXTSEARCH-FUNCTIONS-TABLE) +tsquery1.ToPhrase(tsquery2) | [tsquery_phrase(tsquery1, tsquery2)](https://www.postgresql.org/docs/current/functions-textsearch.html#TEXTSEARCH-FUNCTIONS-TABLE) +tsquery1.ToPhrase(tsquery2, distance) | [tsquery_phrase(tsquery1, tsquery2, distance)](https://www.postgresql.org/docs/current/functions-textsearch.html#TEXTSEARCH-FUNCTIONS-TABLE) +tsvector1.Concat(tsvector2) | [tsvector1 \|\| tsvector2](https://www.postgresql.org/docs/current/functions-textsearch.html#TEXTSEARCH-OPERATORS-TABLE) +tsvector.Delete("x") | [ts_delete(tsvector, 'x')](https://www.postgresql.org/docs/current/functions-textsearch.html#TEXTSEARCH-FUNCTIONS-TABLE) +tsvector.Delete(new[] { "x", "y" }) | [ts_delete(tsvector, ARRAY['x', 'y'])](https://www.postgresql.org/docs/current/functions-textsearch.html#TEXTSEARCH-FUNCTIONS-TABLE) +tsvector.Filter(new[] { "x", "y" }) | [ts_filter(tsvector, ARRAY['x', 'y'])](https://www.postgresql.org/docs/current/functions-textsearch.html#TEXTSEARCH-FUNCTIONS-TABLE) +tsvector.GetLength() | [length(tsvector)](https://www.postgresql.org/docs/current/functions-textsearch.html#TEXTSEARCH-FUNCTIONS-TABLE) +tsvector.Rank(tsquery) | [ts_rank(tsvector, tsquery)](https://www.postgresql.org/docs/current/textsearch-controls.html#TEXTSEARCH-RANKING) +tsvector.RankCoverDensity(tsquery) | [ts_rank_cd(tsvector, tsquery)](https://www.postgresql.org/docs/current/textsearch-controls.html#TEXTSEARCH-RANKING) +tsvector.SetWeight(NpgsqlTsVector.Lexeme.Weight.A)) | [setweight(tsvector, 'A')](https://www.postgresql.org/docs/current/static/textsearch-features.html#TEXTSEARCH-MANIPULATE-TSVECTOR) +tsvector.ToStripped() | [strip(tsvector)](https://www.postgresql.org/docs/current/functions-textsearch.html#TEXTSEARCH-FUNCTIONS-TABLE) EF.Functions.Unaccent(string) | [unaccent(string)](https://www.postgresql.org/docs/current/unaccent.html) EF.Functions.Unaccent(regdictionary, string) | [unaccent(regdictionary, string)](https://www.postgresql.org/docs/current/unaccent.html) From a31b5c7be278125f9b36b5ee6773b0388b03be13 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Sun, 31 Oct 2021 10:11:59 +0100 Subject: [PATCH 078/207] Document DateTime.SpecifyKind translations (#142) And fix wrong ConvertTimeToUtc translation docs --- docs/mapping/translations.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/mapping/translations.md b/docs/mapping/translations.md index 0311e89320..a413ddd381 100644 --- a/docs/mapping/translations.md +++ b/docs/mapping/translations.md @@ -51,7 +51,9 @@ timeSpan.Milliseconds | [floor(date_ timeSpan.Milliseconds | [floor(date_part('millisecond', timeSpan))::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | dateTime1 - dateTime2 | [dateTime1 - dateTime2](https://www.postgresql.org/docs/current/functions-datetime.html#OPERATORS-DATETIME-TABLE) | TimeZoneInfo.ConvertTimeBySystemTimeZoneId(utcDateTime, timezone) | [utcDateTime AT TIME ZONE timezone](https://www.postgresql.org/docs/current/functions-datetime.html#FUNCTIONS-DATETIME-ZONECONVERT) | Added in 6.0, only for timestamptz columns -TimeZoneInfo.ConvertTimeToUtc(nonUtcDateTime) | [nonUtcDateTime AT TIME ZONE timezone](https://www.postgresql.org/docs/current/functions-datetime.html#FUNCTIONS-DATETIME-ZONECONVERT) | Added in 6.0, only for timestamp columns +TimeZoneInfo.ConvertTimeToUtc(nonUtcDateTime) | [nonUtcDateTime::timestamptz](https://www.postgresql.org/docs/current/functions-datetime.html) | Added in 6.0, only for timestamp columns +DateTime.SpecifyKind(utcDateTime, DateTimeKind.Unspecified) | [utcDateTime AT TIME ZONE 'UTC'](https://www.postgresql.org/docs/current/functions-datetime.html#FUNCTIONS-DATETIME-ZONECONVERT) | Added in 6.0, only for timestamptz columns +DateTime.SpecifyKind(nonUtcDateTime, DateTimeKind.Utc) | [nonUtcDateTime AT TIME ZONE 'UTC'](https://www.postgresql.org/docs/current/functions-datetime.html#FUNCTIONS-DATETIME-ZONECONVERT) | Added in 6.0, only for timestamp columns new DateTime(year, month, day) | [make_date(year, month, day)](https://www.postgresql.org/docs/current/functions-datetime.html) | new DateTime(y, m, d, h, m, s) | [make_timestamp(y, m, d, h, m, s)](https://www.postgresql.org/docs/current/functions-datetime.html) | new DateTime(y, m, d, h, m, s, kind) | [make_timestamp or make_timestamptz](https://www.postgresql.org/docs/current/functions-datetime.html), based on `king` | Added in 6.0 From 66e4679c42eb2a0f46c88301aa7470155e0c4d23 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Wed, 3 Nov 2021 15:32:07 +0100 Subject: [PATCH 079/207] Document NodaTime interval mapping (#144) * https://github.com/npgsql/npgsql/issues/4070 * https://github.com/npgsql/efcore.pg/issues/2059 --- docs/release-notes/6.0.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/release-notes/6.0.md b/docs/release-notes/6.0.md index bed1153abe..a21b42a3b2 100644 --- a/docs/release-notes/6.0.md +++ b/docs/release-notes/6.0.md @@ -22,7 +22,7 @@ Other date/time improvements include: * Support for the new [.NET DateOnly and TimeOnly types](https://devblogs.microsoft.com/dotnet/date-time-and-time-zone-enhancements-in-net-6/). * Most [DateTimeOffset](https://docs.microsoft.com/dotnet/api/system.datetimeoffset) members and methods are now translated. * Many NodaTime translations have been added for [ZonedDateTime](https://nodatime.org/3.0.x/api/NodaTime.ZonedDateTime.html), [Period](https://nodatime.org/3.0.x/api/NodaTime.Period.html), [DateInterval](https://nodatime.org/3.0.x/api/NodaTime.DateInterval.html) and others. -* PostgreSQL `daterange` is now mapped to NodaTime [DateInterval](https://nodatime.org/3.0.x/api/NodaTime.DateInterval.html), and most methods on it are translated ([#1998](https://github.com/npgsql/efcore.pg/issues/1998)). +* PostgreSQL `tstzrange` is now mapped to NodaTime [Interval](https://nodatime.org/3.0.x/api/NodaTime.Interval.html), and PostgreSQL `daterange` is now mapped to NodaTime [DateInterval](https://nodatime.org/3.0.x/api/NodaTime.DateInterval.html). Most methods on these types are translated ([#1998](https://github.com/npgsql/efcore.pg/issues/1998), [#2059](https://github.com/npgsql/efcore.pg/issues/2059)). ### Other new features @@ -120,9 +120,9 @@ The changes described above are far-reaching, and may break applications in vari AppContext.SetSwitch("Npgsql.EnableLegacyTimestampBehavior", true); ``` -### NodaTime: daterange is scaffolded as DateInterval by default +### NodaTime: tstzrange and daterange are mapped to Interval and DateInterval by default -When using NodaTime, a PostgreSQL `daterange` column is scaffolded as a [DateInterval](https://nodatime.org/3.0.x/api/NodaTime.DateInterval.html) property instead of a `NpgsqlRange` property ([#1998](https://github.com/npgsql/efcore.pg/issues/1998)). +When using NodaTime, PostgreSQL `tstzrange` columns are scaffolded as [Interval](https://nodatime.org/3.0.x/api/NodaTime.Interval.html) properties instead of `NpgsqlRange` ([#4070](https://github.com/npgsql/npgsql/issues/4070)), and `daterange` columns are scaffolded as [DateInterval](https://nodatime.org/3.0.x/api/NodaTime.DateInterval.html) properties of `NpgsqlRange` ([#1998](https://github.com/npgsql/efcore.pg/issues/1998)). ### Date/time min/max values are now converted to PostgreSQL infinity values by default From 8c505db62542871301cae2970516acfb5ede96d5 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Mon, 8 Nov 2021 14:31:08 +0100 Subject: [PATCH 080/207] Add docs on timestamp generation (#148) Also update GUID generation while we're at it --- docs/modeling/generated-properties.md | 65 ++++++++++++++++++++++++--- 1 file changed, 59 insertions(+), 6 deletions(-) diff --git a/docs/modeling/generated-properties.md b/docs/modeling/generated-properties.md index aedcf26f89..2af95b819c 100644 --- a/docs/modeling/generated-properties.md +++ b/docs/modeling/generated-properties.md @@ -102,20 +102,73 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) ## Guid/UUID Generation -By default, if you specify `ValueGeneratedOnAdd` on a Guid property, a random Guid value will be generated client-side and sent to the database. +By default, for Guid key properties (or if you specify `ValueGeneratedOnAdd` on any Guid property), a random `Guid` value will be generated client-side and sent to the database. -If you prefer to generate values in the database instead, you can do so by specifying `HasDefaultValueSql` on your property. Note that PostgreSQL doesn't include any Guid/UUID generation functions, you must add an extension such as `uuid-ossp` or `pgcrypto`. This can be done by placing the following code in your model's `OnModelCreating`: +If you prefer to generate values in the database instead, you can do so by specifying `HasDefaultValueSql` on your property, and call the function to generate the `Guid` in the SQL expression. Which function to use depends on your PostgreSQL version: + +### [PG 13+](#tab/13) ```c# protected override void OnModelCreating(ModelBuilder modelBuilder) - => modelBuilder.HasPostgresExtension("uuid-ossp") - .Entity() - .Property(e => e.SomeGuidProperty) - .HasDefaultValueSql("uuid_generate_v4()"); +{ + modelBuilder + .Entity() + .Property(e => e.SomeGuidProperty) + .HasDefaultValueSql("gen_random_uuid()"); +} ``` +### [Older](#tab/older) + +Versions of PostgreSQL prior to 13 don't include any Guid/UUID generation functions, but extensions such as `uuid-ossp` or `pgcrypto` exist to fill thie gap. This can be done by placing the following code in your model's `OnModelCreating`: + +```c# +protected override void OnModelCreating(ModelBuilder modelBuilder) +{ + modelBuilder.HasPostgresExtension("uuid-ossp"); + + modelBuilder + .Entity() + .Property(e => e.SomeGuidProperty) + .HasDefaultValueSql("uuid_generate_v4()"); +} +``` + +*** + See [the PostgreSQL docs on UUID for more details](https://www.postgresql.org/docs/current/static/datatype-uuid.html). +## Timestamp generation + +In many scenarios, it's useful to have a column containing the timestamp when the row was originally created. To do this, add a `DateTime` property to your entity type (or `Instant` if using NodaTime) , and configure its default with `HasDefaultValueSql` as follows: + +```c# +protected override void OnModelCreating(ModelBuilder modelBuilder) +{ + modelBuilder + .Entity() + .Property(e => e.SomeDateTimeProperty) + .HasDefaultValueSql("now()"); +} +``` + +In other scenarios, a "last updated" is needed, which is automatically updated every time is modified. Unfortunately, while PostgreSQL supports [generated columns](https://www.postgresql.org/docs/current/ddl-generated-columns.html), the use of functions such as `now()` isn't supported. It's still possible to use database trigger to set this up; triggers can be managed by [adding raw SQL to your migrations](https://docs.microsoft.com/ef/core/managing-schemas/migrations/managing#adding-raw-sql), as follows: + +```sql +CREATE FUNCTION "Blogs_Update_Timestamp_Function"() RETURNS TRIGGER LANGUAGE PLPGSQL AS $$ +BEGIN + NEW."Timestamp" := now(); + RETURN NEW; +END; +$$ + +CREATE TRIGGER "UpdateTimestamp" + BEFORE INSERT OR UPDATE + ON "Blogs" + FOR EACH ROW + EXECUTE FUNCTION "Blogs_Update_Timestamp_Function"(); +``` + ## Computed Columns > [!NOTE] From daa4c3ef3b23673cdc2a1704bc00dbd1463c92f7 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Tue, 9 Nov 2021 11:24:55 +0100 Subject: [PATCH 081/207] Release note on EF support for PG14 column compression (#141) See https://github.com/npgsql/efcore.pg/issues/2062 --- docs/release-notes/6.0.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/release-notes/6.0.md b/docs/release-notes/6.0.md index a21b42a3b2..7ddbc776c8 100644 --- a/docs/release-notes/6.0.md +++ b/docs/release-notes/6.0.md @@ -27,7 +27,8 @@ Other date/time improvements include: ### Other new features * The provider is now fully annotated for nullable reference types. -* Full support for the upcoming PostgreSQL 14 [multirange type](https://www.postgresql.org/docs/14/rangetypes.html), mapped to arrays or lists of `NpgsqlRange` ([#1963](https://github.com/npgsql/efcore.pg/issues/1963)). Includes translation of all major operators and functions, [see the updated docs](../mapping/range.md). +* Full support for the PostgreSQL 14 [multirange type](https://www.postgresql.org/docs/14/rangetypes.html), mapped to arrays or lists of `NpgsqlRange` ([#1963](https://github.com/npgsql/efcore.pg/issues/1963)). Includes translation of all major operators and functions, [see the updated docs](../mapping/range.md). +* Support for PostgreSQL 14 [column compression methods](https://paquier.xyz/postgresql-2/postgres-14-table-compression/) ([#2062](https://github.com/npgsql/efcore.pg/issues/2062)). * Support for the PostgreSQL [ltree](https://www.postgresql.org/docs/current/ltree.html) type, which represents labels of data stored in a hierarchical tree-like structure. Requires PostgreSQL 13 and above. * Multiple spatial translations have been added for NetTopologySuite ([DistanceKnn, <->](https://github.com/npgsql/efcore.pg/issues/1827), [ST_Force2D](https://github.com/npgsql/efcore.pg/issues/1917), [ST_Distance and ST_DWithin with spheriod](https://github.com/npgsql/efcore.pg/issues/1638)). * More translations and better type inference for arrays ([#2026](https://github.com/npgsql/efcore.pg/issues/2026)). From 754bf0be1d738f5a6095071d4cb58a8f77a0c8a8 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Thu, 11 Nov 2021 16:14:14 +0100 Subject: [PATCH 082/207] Add note on TimeZone in the date/time translations page --- docs/mapping/translations.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/docs/mapping/translations.md b/docs/mapping/translations.md index a413ddd381..f3a9d90b13 100644 --- a/docs/mapping/translations.md +++ b/docs/mapping/translations.md @@ -15,6 +15,9 @@ bytes1.SequenceEqual(bytes2) | @bytes = @second | Added in 5.0 ## Date and time functions +> [!NOTE] +> Some of the operations below depend on the concept of a "local time zone" (e.g. `DateTime.Today`). While in .NET this is the machine time zone where .NET is running, the corresponding PostgreSQL translations use the [`TimeZone`](https://www.postgresql.org/docs/current/runtime-config-client.html#GUC-TIMEZONE) connection parameter as the local time zone. + > [!NOTE] > Since version 6.0, many of the below DateTime translations are also supported on DateTimeOffset. From 2775215ea9d88602497b33ce1b2cff83509def38 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Sat, 13 Nov 2021 20:10:56 +0100 Subject: [PATCH 083/207] Add missing semicolon to SQL sample --- docs/modeling/generated-properties.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/modeling/generated-properties.md b/docs/modeling/generated-properties.md index 2af95b819c..ce3559962b 100644 --- a/docs/modeling/generated-properties.md +++ b/docs/modeling/generated-properties.md @@ -160,7 +160,7 @@ BEGIN NEW."Timestamp" := now(); RETURN NEW; END; -$$ +$$; CREATE TRIGGER "UpdateTimestamp" BEFORE INSERT OR UPDATE From 4ac08233a28c763c88cb5224304557f6a38cf516 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Sun, 14 Nov 2021 15:11:23 +0100 Subject: [PATCH 084/207] Breaking change note on default mapping to multirange (#149) See https://github.com/npgsql/efcore.pg/issues/2098 --- docs/release-notes/6.0.md | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/docs/release-notes/6.0.md b/docs/release-notes/6.0.md index 7ddbc776c8..be86b3ed64 100644 --- a/docs/release-notes/6.0.md +++ b/docs/release-notes/6.0.md @@ -150,3 +150,28 @@ This is no longer possible and will cause an exception to be thrown. Instead, us modelBuilder.Entity.Property(e => e.ValueConvertedArray) .HasPostgresArrayConversion(w => w.Value, v => new IntWrapper(v)); ``` + +### Arrays/lists over ranges are mapped to PG14 multiranges + +PostgreSQL 14 introduced [a new multirange type](https://www.postgresql.org/docs/14/rangetypes.html), which is very similar to an array of ranges but supports various range-related operations efficiently. The provider now maps arrays and lists of `NpgsqlRange` to these new types by default. To map them to old-style arrays over ranges in PostgreSQL, [configure the column type explicitly](https://docs.microsoft.com/ef/core/modeling/entity-properties#column-data-types): + +### [Data Annotations](#tab/annotations) + +```c# +[Column(TypeName = "int4range[]")] +public NpgsqlRange[] SomeArrayOverIntNpgsqlRange { get; set;} +``` + +### [Fluent API](#tab/fluent-api) + +```c# +protected override void OnModelCreating(ModelBuilder modelBuilder) +{ + modelBuilder + .Entity() + .Property(e => e.SomeArrayOverIntNpgsqlRange) + .HasColumnType("int4range[]"); +} +``` + +*** From d88575c926ebf87be94c1d8e13032aefe9392f28 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Mon, 22 Nov 2021 14:01:59 +0100 Subject: [PATCH 085/207] Document added translations on DateTimeOffset (#151) DateTime, UtcDateTime, LocalDateTime. See https://github.com/npgsql/efcore.pg/pull/2120 --- docs/mapping/translations.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/docs/mapping/translations.md b/docs/mapping/translations.md index f3a9d90b13..a47b91125a 100644 --- a/docs/mapping/translations.md +++ b/docs/mapping/translations.md @@ -46,6 +46,9 @@ dateTime.Second | [date_part(' dateTime.Year | [date_part('year', dateTime)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | dateTime.ToUniversalTime | [dateTime::timestamptz](https://www.postgresql.org/docs/current/datatype-datetime.html#id-1.5.7.13.18.7) | Added in 6.0 dateTime.ToLocalTime | [dateTime::timestamp](https://www.postgresql.org/docs/current/datatype-datetime.html#id-1.5.7.13.18.7) | Added in 6.0 +dateTimeOffset.DateTime | [dateTimeOffset AT TIME ZONE 'UTC'](https://www.postgresql.org/docs/current/functions-datetime.html#FUNCTIONS-DATETIME-ZONECONVERT) | Added in 6.0 +dateTimeOffset.UtcDateTime | No PG operation (.NET-side conversion from DateTimeOffset to DateTime only) | Added in 6.0 +dateTimeOffset.LocalDateTime | [dateTimeOffset::timestamp](https://www.postgresql.org/docs/current/datatype-datetime.html#id-1.5.7.13.18.7) | Added in 6.0 timeSpan.Days | [floor(date_part('day', timeSpan))::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | timeSpan.Hours | [floor(date_part('hour', timeSpan))::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | timeSpan.Minutes | [floor(date_part('minute', timeSpan))::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | From 8ae70a3a517a0a6eff8f887052ef24d85122fa22 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Thu, 25 Nov 2021 13:38:38 +0100 Subject: [PATCH 086/207] Tweaks to 6.0 timestamp breaking changes --- docs/release-notes/6.0.md | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/docs/release-notes/6.0.md b/docs/release-notes/6.0.md index be86b3ed64..7cc3aa0cd4 100644 --- a/docs/release-notes/6.0.md +++ b/docs/release-notes/6.0.md @@ -44,8 +44,10 @@ The full list of issues for this release is [available here](https://github.com/ #### Quick summary -* Most applications want to store UTC timestamps in the database. To do this, migrate your `timestamp without time zone` columns to `timestamp with time zone` ([see migration notes below](#migrating-columns-from-timestamp-to-timestamptz)), and always use DateTime with Kind=Utc when interacting with Npgsql. -* For the few cases where non-UTC timestamps are desired, add explicit configuration to your properties to be `timestamp without time zone` +* In many cases, is makes sense to store UTC timestamps in the database. To do this, migrate your `timestamp without time zone` columns to `timestamp with time zone` ([see migration notes below](#migrating-columns-from-timestamp-to-timestamptz)), and always use either DateTime with Kind=Utc or DateTimeOffset with offset 0. + * If using NodaTime (recommended), use either [Instant](https://nodatime.org/3.0.x/api/NodaTime.Instant.html) or [ZonedDateTime](https://nodatime.org/3.0.x/api/NodaTime.ZonedDateTime.html) with time zone UTC. +* To store non-UTC timestamps, use DateTime with Kind=Unspecified and [add explicit configuration](https://docs.microsoft.com/ef/core/modeling/entity-properties#column-data-types) to your properties to be `timestamp without time zone`. + * If using NodaTime (recommended), use [LocalDateTime](https://nodatime.org/3.0.x/api/NodaTime.LocalDateTime.html) (no explicit column configuration is required). #### Detailed notes @@ -115,7 +117,7 @@ This will ensure that no time zone conversions will be applied when converting t #### Opting out of the new timestamp mapping logic -The changes described above are far-reaching, and may break applications in various ways. You can upgrade to version 6.0 but opt out of the new mapping by enabling the `Npgsql.EnableLegacyTimestampBehavior` [AppContext switch](https://docs.microsoft.com/en-us/dotnet/api/system.appcontext?view=net-5.0). To do this and revert to the legacy timestamp behavior, add the following at the start of your application, before any Npgsql or EF Core operations are invoked: +The changes described above are far-reaching, and may break applications in various ways. You can upgrade to version 6.0 but opt out of the new mapping by enabling the `Npgsql.EnableLegacyTimestampBehavior` [AppContext switch](https://docs.microsoft.com/en-us/dotnet/api/system.appcontext?view=net-5.0). To do this and revert to the legacy timestamp behavior, add the following to your context's constructor, before any Npgsql or EF Core operations are invoked: ```c# AppContext.SetSwitch("Npgsql.EnableLegacyTimestampBehavior", true); From 0284ee10ab1264a193cabc3ceec062c68217e864 Mon Sep 17 00:00:00 2001 From: alewmt Date: Tue, 30 Nov 2021 13:32:39 +0300 Subject: [PATCH 087/207] Correct UseDatabaseTemplate method name (#153) --- docs/misc/database-creation.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/misc/database-creation.md b/docs/misc/database-creation.md index 63a6a89e2e..08ec5eb690 100644 --- a/docs/misc/database-creation.md +++ b/docs/misc/database-creation.md @@ -21,7 +21,7 @@ which will be copied as the basis for the new one. This can be useful for includ ```c# protected override void OnModelCreating(ModelBuilder modelBuilder) - => modelBuilder.HasDatabaseTemplate("my_template_db"); + => modelBuilder.UseDatabaseTemplate("my_template_db"); ``` ## Setting a tablespace From 1a1207b17b74f67b432ee45ae586d7cbc7ea0a5c Mon Sep 17 00:00:00 2001 From: NathanielBlack Date: Thu, 2 Dec 2021 15:48:35 +0100 Subject: [PATCH 088/207] Update enum.md (#159) Removing enum-values is not supported by Postgres. --- docs/mapping/enum.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/mapping/enum.md b/docs/mapping/enum.md index f7f9c2bb0f..2c1b9b0bd6 100644 --- a/docs/mapping/enum.md +++ b/docs/mapping/enum.md @@ -75,7 +75,7 @@ using (var ctx = new MyDbContext()) ## Altering enum definitions -Although PostgreSQL allows [altering enum types](https://www.postgresql.org/docs/current/static/sql-altertype.html), the Npgsql provider currently does not generate SQL for those operations (beyond creating and dropping the entire type). If you to add, remove or rename enum values, you'll have to include raw SQL in your migrations (this is quite easy to do). As always, test your migrations carefully before running them on production databases. +Although PostgreSQL allows [altering enum types](https://www.postgresql.org/docs/current/static/sql-altertype.html), the Npgsql provider currently does not generate SQL for those operations (beyond creating and dropping the entire type). If you to add or rename enum values (removal is not supported by PostgreSQL), you'll have to include raw SQL in your migrations (this is quite easy to do). As always, test your migrations carefully before running them on production databases. ## Scaffolding from an existing database From 7c5421e6cd47d7bfedda7e6c55c16c75d250d0a9 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Thu, 9 Dec 2021 12:10:51 +0200 Subject: [PATCH 089/207] Added 6.0 breaking change note about Trigrams and FuzzyStringMatch (#160) --- docs/release-notes/6.0.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/release-notes/6.0.md b/docs/release-notes/6.0.md index 7cc3aa0cd4..c547f13c52 100644 --- a/docs/release-notes/6.0.md +++ b/docs/release-notes/6.0.md @@ -177,3 +177,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) ``` *** + +### Trigrams and FuzzyStringMatch plugins are now built-in + +The Npgsql.EntityFrameworkCore.PostgreSQL.Trigrams and Npgsql.EntityFrameworkCore.PostgreSQL.FuzzyStringMatch plugins have been integrated into the main provider; as a result, there are no 6.0 versions of these nuget packages - simply remove the package references from your project when upgrading to 6.0.0. From 5a2230fe64a764f1d50c75c9de90d360ddab2187 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Mon, 13 Dec 2021 23:58:48 +0100 Subject: [PATCH 090/207] Typo --- docs/mapping/translations.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/mapping/translations.md b/docs/mapping/translations.md index a47b91125a..67178597cb 100644 --- a/docs/mapping/translations.md +++ b/docs/mapping/translations.md @@ -62,7 +62,7 @@ DateTime.SpecifyKind(utcDateTime, DateTimeKind.Unspecified) | [utcDateTime DateTime.SpecifyKind(nonUtcDateTime, DateTimeKind.Utc) | [nonUtcDateTime AT TIME ZONE 'UTC'](https://www.postgresql.org/docs/current/functions-datetime.html#FUNCTIONS-DATETIME-ZONECONVERT) | Added in 6.0, only for timestamp columns new DateTime(year, month, day) | [make_date(year, month, day)](https://www.postgresql.org/docs/current/functions-datetime.html) | new DateTime(y, m, d, h, m, s) | [make_timestamp(y, m, d, h, m, s)](https://www.postgresql.org/docs/current/functions-datetime.html) | -new DateTime(y, m, d, h, m, s, kind) | [make_timestamp or make_timestamptz](https://www.postgresql.org/docs/current/functions-datetime.html), based on `king` | Added in 6.0 +new DateTime(y, m, d, h, m, s, kind) | [make_timestamp or make_timestamptz](https://www.postgresql.org/docs/current/functions-datetime.html), based on `kind` | Added in 6.0 > [!NOTE] > See also Npgsql's [NodaTime support](/efcore/mapping/nodatime.html). From 8f7a0b345ce478fb135ad8b1fc8e376f59973aa6 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Sat, 18 Dec 2021 23:39:19 +0100 Subject: [PATCH 091/207] Document random translation --- docs/mapping/translations.md | 47 ++++++++++++++++++------------------ 1 file changed, 24 insertions(+), 23 deletions(-) diff --git a/docs/mapping/translations.md b/docs/mapping/translations.md index 67178597cb..aa6209f5f3 100644 --- a/docs/mapping/translations.md +++ b/docs/mapping/translations.md @@ -105,29 +105,30 @@ EF.Functions.Set7BitMac8(macaddr8) | [macaddr8_set7bit(macaddr8)]( ## Numeric functions -.NET | SQL ------------------------ | -------------------- -Math.Abs(value) | abs(value) -Math.Acos(d) | acos(d) -Math.Asin(d) | asin(d) -Math.Atan(d) | atan(d) -Math.Atan2(y, x) | atan2(y, x) -Math.Ceiling(d) | ceiling(d) -Math.Cos(d) | cos(d) -Math.Exp(d) | exp(d) -Math.Floor(d) | floor(d) -Math.Log(d) | ln(d) -Math.Log10(d) | log(d) -Math.Max(x, y) | greatest(x, y) -Math.Min(x, y) | least(x, y) -Math.Pow(x, y) | power(x, y) -Math.Round(d) | round(d) -Math.Round(d, decimals) | round(d, decimals) -Math.Sin(a) | sin(a) -Math.Sign(value) | sign(value)::int -Math.Sqrt(d) | sqrt(d) -Math.Tan(a) | tan(a) -Math.Truncate(d) | trunc(d) +.NET | SQL | Notes +----------------------- | ------------------ | ----- +Math.Abs(value) | abs(value) | +Math.Acos(d) | acos(d) | +Math.Asin(d) | asin(d) | +Math.Atan(d) | atan(d) | +Math.Atan2(y, x) | atan2(y, x) | +Math.Ceiling(d) | ceiling(d) | +Math.Cos(d) | cos(d) | +Math.Exp(d) | exp(d) | +Math.Floor(d) | floor(d) | +Math.Log(d) | ln(d) | +Math.Log10(d) | log(d) | +Math.Max(x, y) | greatest(x, y) | +Math.Min(x, y) | least(x, y) | +Math.Pow(x, y) | power(x, y) | +Math.Round(d) | round(d) | +Math.Round(d, decimals) | round(d, decimals) | +Math.Sin(a) | sin(a) | +Math.Sign(value) | sign(value)::int | +Math.Sqrt(d) | sqrt(d) | +Math.Tan(a) | tan(a) | +Math.Truncate(d) | trunc(d) | +EF.Functions.Random() | random() | Added in 6.0 ## String functions From 81b80d3eb90706ab827ff6f7700d9ec18bfa78ab Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Fri, 31 Dec 2021 21:09:23 +0100 Subject: [PATCH 092/207] Move EFCore.PG 2.1 to out of support --- docs/toc.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/toc.yml b/docs/toc.yml index 018feb63c9..f6b9c020b6 100644 --- a/docs/toc.yml +++ b/docs/toc.yml @@ -8,12 +8,12 @@ href: release-notes/5.0.md - name: "3.1" href: release-notes/3.1.md - - name: "2.1" - href: release-notes/2.1.md - name: Out of support items: - name: "2.2" href: release-notes/2.2.md + - name: "2.1" + href: release-notes/2.1.md - name: "2.0" href: release-notes/2.0.md - name: "1.1" From 59f659ece6cb45464b8f3921f7d973633529b0ef Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Wed, 12 Jan 2022 01:42:00 +0200 Subject: [PATCH 093/207] Correct full-text search translations (#174) See https://github.com/npgsql/efcore.pg/issues/2210#issuecomment-1010463456 --- docs/mapping/full-text-search.md | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/docs/mapping/full-text-search.md b/docs/mapping/full-text-search.md index cea422d835..bfbd0ad346 100644 --- a/docs/mapping/full-text-search.md +++ b/docs/mapping/full-text-search.md @@ -154,17 +154,17 @@ Almost all PostgreSQL full text search functions can be called through LINQ quer EF.Functions.ToTsVector(string) | [to_tsvector(string)](https://www.postgresql.org/docs/current/static/textsearch-controls.html#TEXTSEARCH-PARSING-DOCUMENTS) EF.Functions.ToTsVector("english", string) | [to_tsvector('english'::regconfig, string)](https://www.postgresql.org/docs/current/static/textsearch-controls.html#TEXTSEARCH-PARSING-DOCUMENTS) EF.Functions.ToTsQuery(string)) | [to_tsquery(string)](https://www.postgresql.org/docs/current/static/textsearch-controls.html#TEXTSEARCH-PARSING-QUERIES) -EF.Functions.ToTsQuery("english", string)) | [to_tsquery('english'::regconfig, string)](https://www.postgresql.org/docs/current/static/textsearch-controls.html#TEXTSEARCH-PARSING-QUERIES) -EF.Functions.PlainToTsQuery(string)) | [plainto_tsquery(string)](https://www.postgresql.org/docs/current/static/textsearch-controls.html#TEXTSEARCH-PARSING-QUERIES) -EF.Functions.PlainToTsQuery("english", string)) | [plainto_tsquery('english'::regconfig, string)](https://www.postgresql.org/docs/current/static/textsearch-controls.html#TEXTSEARCH-PARSING-QUERIES) -EF.Functions.PhraseToTsQuery(string)) | [phraseto_tsquery(string)](https://www.postgresql.org/docs/current/static/textsearch-controls.html#TEXTSEARCH-PARSING-QUERIES) -EF.Functions.PhraseToTsQuery("english", string)) | [phraseto_tsquery('english'::regconfig, string)](https://www.postgresql.org/docs/current/static/textsearch-controls.html#TEXTSEARCH-PARSING-QUERIES) -EF.Functions.WebSearchToTsQuery(string)) | [websearch_to_tsquery(string)](https://www.postgresql.org/docs/current/static/textsearch-controls.html#TEXTSEARCH-PARSING-QUERIES) -EF.Functions.WebSearchToTsQuery("english", string)) | [websearch_to_tsquery('english'::regconfig, string)](https://www.postgresql.org/docs/current/static/textsearch-controls.html#TEXTSEARCH-PARSING-QUERIES) +EF.Functions.ToTsQuery("english", string ) | [to_tsquery('english'::regconfig, string)](https://www.postgresql.org/docs/current/static/textsearch-controls.html#TEXTSEARCH-PARSING-QUERIES) +EF.Functions.PlainToTsQuery(string) | [plainto_tsquery(string)](https://www.postgresql.org/docs/current/static/textsearch-controls.html#TEXTSEARCH-PARSING-QUERIES) +EF.Functions.PlainToTsQuery("english", string) | [plainto_tsquery('english'::regconfig, string)](https://www.postgresql.org/docs/current/static/textsearch-controls.html#TEXTSEARCH-PARSING-QUERIES) +EF.Functions.PhraseToTsQuery(string) | [phraseto_tsquery(string)](https://www.postgresql.org/docs/current/static/textsearch-controls.html#TEXTSEARCH-PARSING-QUERIES) +EF.Functions.PhraseToTsQuery("english", string) | [phraseto_tsquery('english'::regconfig, string)](https://www.postgresql.org/docs/current/static/textsearch-controls.html#TEXTSEARCH-PARSING-QUERIES) +EF.Functions.WebSearchToTsQuery(string) | [websearch_to_tsquery(string)](https://www.postgresql.org/docs/current/static/textsearch-controls.html#TEXTSEARCH-PARSING-QUERIES) +EF.Functions.WebSearchToTsQuery("english", string) | [websearch_to_tsquery('english'::regconfig, string)](https://www.postgresql.org/docs/current/static/textsearch-controls.html#TEXTSEARCH-PARSING-QUERIES) EF.functions.ArrayToTsVector(new[] { "a", "b" }) | [array_to_tsvector(ARRAY['a', 'b'])](https://www.postgresql.org/docs/current/functions-textsearch.html#TEXTSEARCH-FUNCTIONS-TABLE) -NpgsqlTsVector.Parse(string)) | [CAST(string AS tsvector)](https://www.postgresql.org/docs/current/static/sql-expressions.html#SQL-SYNTAX-TYPE-CASTS) -NpgsqlTsQuery.Parse(string)) | [CAST(queryString AS tsquery)](https://www.postgresql.org/docs/current/static/sql-expressions.html#SQL-SYNTAX-TYPE-CASTS) -tsvector.Matches(string)) | [tsvector @@ string](https://www.postgresql.org/docs/current/static/textsearch-intro.html#TEXTSEARCH-MATCHING) +NpgsqlTsVector.Parse(string) | [CAST(string AS tsvector)](https://www.postgresql.org/docs/current/static/sql-expressions.html#SQL-SYNTAX-TYPE-CASTS) +NpgsqlTsQuery.Parse(string) | [CAST(queryString AS tsquery)](https://www.postgresql.org/docs/current/static/sql-expressions.html#SQL-SYNTAX-TYPE-CASTS) +tsvector.Matches(string) | [tsvector @@ plainto_tsquery(string)](https://www.postgresql.org/docs/current/static/textsearch-intro.html#TEXTSEARCH-MATCHING) tsvector.Matches(tsquery) | [tsvector @@ tsquery](https://www.postgresql.org/docs/current/static/textsearch-controls.html#TEXTSEARCH-PARSING-QUERIES) tsquery1.And(tsquery2) | [tsquery1 && tsquery2](https://www.postgresql.org/docs/current/static/textsearch-features.html#TEXTSEARCH-MANIPULATE-TSQUERY) tsquery1.Or(tsquery2) | [tsquery1 \|\| tsquery2](https://www.postgresql.org/docs/current/static/textsearch-features.html#TEXTSEARCH-MANIPULATE-TSQUERY) @@ -185,7 +185,7 @@ tsvector.Filter(new[] { "x", "y" }) | [t tsvector.GetLength() | [length(tsvector)](https://www.postgresql.org/docs/current/functions-textsearch.html#TEXTSEARCH-FUNCTIONS-TABLE) tsvector.Rank(tsquery) | [ts_rank(tsvector, tsquery)](https://www.postgresql.org/docs/current/textsearch-controls.html#TEXTSEARCH-RANKING) tsvector.RankCoverDensity(tsquery) | [ts_rank_cd(tsvector, tsquery)](https://www.postgresql.org/docs/current/textsearch-controls.html#TEXTSEARCH-RANKING) -tsvector.SetWeight(NpgsqlTsVector.Lexeme.Weight.A)) | [setweight(tsvector, 'A')](https://www.postgresql.org/docs/current/static/textsearch-features.html#TEXTSEARCH-MANIPULATE-TSVECTOR) +tsvector.SetWeight(NpgsqlTsVector.Lexeme.Weight.A) | [setweight(tsvector, 'A')](https://www.postgresql.org/docs/current/static/textsearch-features.html#TEXTSEARCH-MANIPULATE-TSVECTOR) tsvector.ToStripped() | [strip(tsvector)](https://www.postgresql.org/docs/current/functions-textsearch.html#TEXTSEARCH-FUNCTIONS-TABLE) EF.Functions.Unaccent(string) | [unaccent(string)](https://www.postgresql.org/docs/current/unaccent.html) EF.Functions.Unaccent(regdictionary, string) | [unaccent(regdictionary, string)](https://www.postgresql.org/docs/current/unaccent.html) From 0be6e2df63a204a3b6b9d8f90c67acf02aa542e1 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Tue, 25 Jan 2022 22:23:23 +0100 Subject: [PATCH 094/207] Add semicolon to TimeZone setting in migration --- docs/release-notes/6.0.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/release-notes/6.0.md b/docs/release-notes/6.0.md index c547f13c52..c931309b18 100644 --- a/docs/release-notes/6.0.md +++ b/docs/release-notes/6.0.md @@ -104,7 +104,7 @@ When converting the `timestamp without time zone` column to `timestamp with time This means that your new `timestamptz` column now contains 10:00 UTC, which is probably not what you want: if the original values were in fact UTC values, you need them to be preserved as-is, changing only the column type. To do this, edit your migration and add the following to the top of your migration's Up and Down methods: ```c# -migrationBuilder.Sql("SET TimeZone='UTC'"); +migrationBuilder.Sql("SET TimeZone='UTC';"); ``` This will ensure that no time zone conversions will be applied when converting the columns: From 22cd22c75928fee2ebfb3d373cb30618e596d6be Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Wed, 26 Jan 2022 17:38:35 +0200 Subject: [PATCH 095/207] Document Total* members translation on TimeSpan (#178) See https://github.com/npgsql/efcore.pg/pull/2243 --- docs/mapping/translations.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/docs/mapping/translations.md b/docs/mapping/translations.md index aa6209f5f3..61d640976b 100644 --- a/docs/mapping/translations.md +++ b/docs/mapping/translations.md @@ -55,6 +55,11 @@ timeSpan.Minutes | [floor(date_ timeSpan.Seconds | [floor(date_part('second', timeSpan))::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | timeSpan.Milliseconds | [floor(date_part('millisecond', timeSpan))::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | timeSpan.Milliseconds | [floor(date_part('millisecond', timeSpan))::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | +timeSpan.TotalMilliseconds | [date_part('epoch', interval) / 0.001](https://www.postgresql.org/docs/current/functions-datetime.html) | Added in 6.0 +timeSpan.TotalSeconds | [date_part('epoch', interval)](https://www.postgresql.org/docs/current/functions-datetime.html) | Added in 6.0 +timeSpan.TotalMinutes | [date_part('epoch', interval) / 60.0](https://www.postgresql.org/docs/current/functions-datetime.html) | Added in 6.0 +timeSpan.TotalDays | [date_part('epoch', interval) / 86400.0](https://www.postgresql.org/docs/current/functions-datetime.html) | Added in 6.0 +timeSpan.TotalHours | [date_part('epoch', interval) / 3600.0](https://www.postgresql.org/docs/current/functions-datetime.html) | Added in 6.0 dateTime1 - dateTime2 | [dateTime1 - dateTime2](https://www.postgresql.org/docs/current/functions-datetime.html#OPERATORS-DATETIME-TABLE) | TimeZoneInfo.ConvertTimeBySystemTimeZoneId(utcDateTime, timezone) | [utcDateTime AT TIME ZONE timezone](https://www.postgresql.org/docs/current/functions-datetime.html#FUNCTIONS-DATETIME-ZONECONVERT) | Added in 6.0, only for timestamptz columns TimeZoneInfo.ConvertTimeToUtc(nonUtcDateTime) | [nonUtcDateTime::timestamptz](https://www.postgresql.org/docs/current/functions-datetime.html) | Added in 6.0, only for timestamp columns From 8bbd7eab336f58a3f20cb1ca50f9a41dd276cb29 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Thu, 10 Feb 2022 12:25:44 +0200 Subject: [PATCH 096/207] Add caution note for instance SSL callbacks (#186) See https://github.com/npgsql/efcore.pg/issues/2265 --- docs/misc/other.md | 3 +++ docs/modeling/indexes.md | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/docs/misc/other.md b/docs/misc/other.md index 2e06eaef7f..21fbcea228 100644 --- a/docs/misc/other.md +++ b/docs/misc/other.md @@ -42,6 +42,9 @@ protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) You may also consider passing `Trust Server Certificate=true` in your connection string to make Npgsql accept whatever certificate your PostgreSQL provides (useful for self-signed certificates). +> [!CAUTION] +> When specifying the options via `OnConfiguring`, make sure that the callbacks you pass in are static methods. Passing in instance methods causes EF Core to create a new service provider for each context instance, which can degrade performance in a significant way. + ## Comments PostgreSQL allows you to [attach comments](https://www.postgresql.org/docs/current/static/sql-syntax-lexical.html#SQL-SYNTAX-COMMENTS) to database objects, which can help explain their purpose for someone examining the schema. The Npgsql EF Core provider supports this for tables or columns, simply set the comment in your model's `OnModelCreating` as follows: diff --git a/docs/modeling/indexes.md b/docs/modeling/indexes.md index 344b4d4eb6..b478856d11 100644 --- a/docs/modeling/indexes.md +++ b/docs/modeling/indexes.md @@ -21,7 +21,7 @@ CREATE INDEX "IX_Blog_Id" ON blogs ("Id") INCLUDE ("Name"); ## PostgreSQL index methods -PostgreSQL supports a number of _index methods_, or _types_. These are specified at index creation time via the `USING _method_` clause, see the [PostgreSQL docs for `CREATE INDEX`](https://www.postgresql.org/docs/current/static/sql-createindex.html) and [this page](https://www.postgresql.org/docs/current/static/indexes-types.html) for information on the different types. +PostgreSQL supports a number of *index methods*, or *types*. These are specified at index creation time via the `USING ` clause, see the [PostgreSQL docs for `CREATE INDEX`](https://www.postgresql.org/docs/current/static/sql-createindex.html) and [this page](https://www.postgresql.org/docs/current/static/indexes-types.html) for information on the different types. The Npgsql EF Core provider allows you to specify the index method to be used by calling `HasMethod()` on your index in your context's `OnModelCreating` method: From 3b7fe39a5d70327c04fd27f68d4bb2b1bfd4ec65 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Tue, 15 Feb 2022 21:58:20 +0100 Subject: [PATCH 097/207] Update ICU collations doc link Closes #188 --- docs/misc/collations-and-case-sensitivity.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/misc/collations-and-case-sensitivity.md b/docs/misc/collations-and-case-sensitivity.md index cd1d9c3d14..c0b6f4efb0 100644 --- a/docs/misc/collations-and-case-sensitivity.md +++ b/docs/misc/collations-and-case-sensitivity.md @@ -22,7 +22,7 @@ In PostgreSQL, collations are first-class, named database objects which can be c modelBuilder.HasCollation("my_collation", locale: "en-u-ks-primary", provider: "icu", deterministic: false); ``` -This creates a collation with the name `my_collation`: this is an arbitrary name you can choose, which you will be specifying later when assigning the collation to columns. The rest of the parameters instruct PostgreSQL to create a non-deterministic, case-insensitive ICU collation. ICU collations are very powerful, and allow you to specify precise rules with regards to case, accents and other textual aspects. Consult [the ICU docs](http://userguide.icu-project.org/collation) for more information on supported features and keywords. +This creates a collation with the name `my_collation`: this is an arbitrary name you can choose, which you will be specifying later when assigning the collation to columns. The rest of the parameters instruct PostgreSQL to create a non-deterministic, case-insensitive ICU collation. ICU collations are very powerful, and allow you to specify precise rules with regards to case, accents and other textual aspects. Consult [the ICU docs](https://unicode-org.github.io/icu/userguide/collation/) for more information on supported features and keywords. ### Column collation From f01ae1dd502c5aa40b7907334c879f5457c601bc Mon Sep 17 00:00:00 2001 From: Artur Drobinskiy Date: Fri, 25 Feb 2022 15:57:15 +0700 Subject: [PATCH 098/207] Fix typo in json.md (#191) --- docs/mapping/json.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/mapping/json.md b/docs/mapping/json.md index e573032f3c..e4f201253b 100644 --- a/docs/mapping/json.md +++ b/docs/mapping/json.md @@ -225,7 +225,7 @@ EF.Functions.JsonContained(@"{""Name"": ""Joe"", ""Age"": 25}", customer) | EF.Functions.JsonExists(customer, "Age") | [customer ? 'Age'](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) EF.Functions.JsonExistsAny(customer, "Age", "Address") | [customer ?\| ARRAY['Age','Address']](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) EF.Functions.JsonExistsAll(customer, "Age", "Address") | [customer ?& ARRAY['Age','Address']](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) -EF.Functions.JsonTypeof(customer.GetProperty("Age") == "number") | [jsonb_typeof(customer->'Age') = 'number'](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-PROCESSING-TABLE) +EF.Functions.JsonTypeof(customer.GetProperty("Age")) == "number" | [jsonb_typeof(customer->'Age') = 'number'](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-PROCESSING-TABLE) *** From eeddae7cbe5189a87a1152b74421a832094f190c Mon Sep 17 00:00:00 2001 From: Pieter-Jan Briers Date: Thu, 7 Apr 2022 11:01:48 +0200 Subject: [PATCH 099/207] Add missing .HasMethod("GIN") in FTS example (#196) --- docs/mapping/full-text-search.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/mapping/full-text-search.md b/docs/mapping/full-text-search.md index bfbd0ad346..d66041acf2 100644 --- a/docs/mapping/full-text-search.md +++ b/docs/mapping/full-text-search.md @@ -115,6 +115,7 @@ Version 5.0.0 of the provider includes sugar for defining the appropriate expres ```c# modelBuilder.Entity() .HasIndex(b => new { b.Title, b.Description }) + .HasMethod("GIN") .IsTsVectorExpressionIndex("english"); ``` From 061f5a357aaed8c2312f2c3883387e7a9030de6a Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Fri, 15 Apr 2022 20:28:50 +0200 Subject: [PATCH 100/207] Fix LTree translations (#198) --- docs/mapping/translations.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/mapping/translations.md b/docs/mapping/translations.md index 61d640976b..50316970cd 100644 --- a/docs/mapping/translations.md +++ b/docs/mapping/translations.md @@ -208,17 +208,17 @@ The below translations are for working with label trees from the PostgreSQL [`lt .NET | SQL ----------------------------------------------------------------- | -------------------- ltree1.IsAncestorOf(ltree2) | ltree1 @> ltree2 -ltree1.IsDescendant(ltree2) | ltree1 <@ ltree2 +ltree1.IsDescendantOf(ltree2) | ltree1 <@ ltree2 ltree.MatchesLQuery(lquery) | ltree ~ lquery ltree.MatchesLTxtQuery(ltxtquery) | ltree @ ltxtquery lqueries.Any(q => ltree.MatchesLQuery(q)) | ltree ? lqueries ltrees.Any(t => t.IsAncestorOf(ltree)) | ltrees @> ltree -ltrees.Any(t => t.IsDescendant(ltree)) | ltrees <@ ltree +ltrees.Any(t => t.IsDescendantOf(ltree)) | ltrees <@ ltree ltrees.Any(t => t.MatchesLQuery(lquery)) | ltrees ~ ltree ltrees.Any(t => t.MatchesLTxtQuery(ltxtquery)) | ltrees @ ltxtquery ltrees.Any(t => lqueries.Any(q => t.MatchesLQuery(q))) | ltrees ? lqueries ltrees.FirstOrDefault(l => l.IsAncestorOf(ltree)) | ltrees ?@> ltree -ltrees.FirstOrDefault(l => l.IsDescendant(ltree)) | ltrees ?<@ ltree +ltrees.FirstOrDefault(l => l.IsDescendantOf(ltree)) | ltrees ?<@ ltree ltrees.FirstOrDefault(l => l.MatchesLQuery(lquery)) | ltrees ?~ ltree ltrees.FirstOrDefault(l => l.MatchesLTxtQuery(ltxtquery)) | ltrees ?@ ltree ltree.Subtree(0, 1) | subltree(ltree, 0, 1) From 62ec95544f43817b5118b9789125f29b8c2ce77b Mon Sep 17 00:00:00 2001 From: neokske <33809012+neokske@users.noreply.github.com> Date: Tue, 19 Apr 2022 18:06:07 +0200 Subject: [PATCH 101/207] Update 6.0.md (#200) Fixing a little typo from `is` to `it` --- docs/release-notes/6.0.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/release-notes/6.0.md b/docs/release-notes/6.0.md index c931309b18..c5d3f0ebff 100644 --- a/docs/release-notes/6.0.md +++ b/docs/release-notes/6.0.md @@ -44,7 +44,7 @@ The full list of issues for this release is [available here](https://github.com/ #### Quick summary -* In many cases, is makes sense to store UTC timestamps in the database. To do this, migrate your `timestamp without time zone` columns to `timestamp with time zone` ([see migration notes below](#migrating-columns-from-timestamp-to-timestamptz)), and always use either DateTime with Kind=Utc or DateTimeOffset with offset 0. +* In many cases, it makes sense to store UTC timestamps in the database. To do this, migrate your `timestamp without time zone` columns to `timestamp with time zone` ([see migration notes below](#migrating-columns-from-timestamp-to-timestamptz)), and always use either DateTime with Kind=Utc or DateTimeOffset with offset 0. * If using NodaTime (recommended), use either [Instant](https://nodatime.org/3.0.x/api/NodaTime.Instant.html) or [ZonedDateTime](https://nodatime.org/3.0.x/api/NodaTime.ZonedDateTime.html) with time zone UTC. * To store non-UTC timestamps, use DateTime with Kind=Unspecified and [add explicit configuration](https://docs.microsoft.com/ef/core/modeling/entity-properties#column-data-types) to your properties to be `timestamp without time zone`. * If using NodaTime (recommended), use [LocalDateTime](https://nodatime.org/3.0.x/api/NodaTime.LocalDateTime.html) (no explicit column configuration is required). From a67d0b6d44dfb6749c5520aa18a430148e25ce2a Mon Sep 17 00:00:00 2001 From: JohnCgp <73995615+JohnCgp@users.noreply.github.com> Date: Fri, 22 Apr 2022 13:44:13 +0200 Subject: [PATCH 102/207] Update concurrency.md (#202) Add link to SO question that illustrates the issue with having `xmin` be a shadow property, and how the entity therefore cannot be passed between contexts. --- docs/modeling/concurrency.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/modeling/concurrency.md b/docs/modeling/concurrency.md index ebad26aea2..32045c0a4b 100644 --- a/docs/modeling/concurrency.md +++ b/docs/modeling/concurrency.md @@ -17,7 +17,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) .UseXminAsConcurrencyToken(); ``` -Note that by default, this will set up a [shadow property](https://docs.microsoft.com/ef/core/modeling/shadow-properties) called `xmin` on your entity. This means that when you load an entity from the database, the value of `xmin` will be stored in the context, making it impossible to use that instance with another context (without reloading the entity). If you plan to pass instances between different contexts, consider adding an `xmin` property of type `uint` on your entity; this will automatically cause the concurrency token to be stored on the instance instead: +Note that by default, this will set up a [shadow property](https://docs.microsoft.com/ef/core/modeling/shadow-properties) called `xmin` on your entity. This means that when you load an entity from the database, the value of `xmin` will be stored in the context, making it [impossible to use that instance with another context](https://stackoverflow.com/a/60871156) (without reloading the entity). If you plan to pass instances between different contexts, consider adding an `xmin` property of type `uint` on your entity; this will automatically cause the concurrency token to be stored on the instance instead: ```c# class Blog From 5fd92069d764f7c693de29f884948c68d14e0829 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Mon, 25 Apr 2022 12:09:09 +0200 Subject: [PATCH 103/207] Document obsoletion of EF default column collations (#203) Closes #194 --- docs/misc/collations-and-case-sensitivity.md | 15 +++++++--- docs/release-notes/7.0.md | 29 ++++++++++++++++++++ 2 files changed, 40 insertions(+), 4 deletions(-) create mode 100644 docs/release-notes/7.0.md diff --git a/docs/misc/collations-and-case-sensitivity.md b/docs/misc/collations-and-case-sensitivity.md index c0b6f4efb0..4286c5b653 100644 --- a/docs/misc/collations-and-case-sensitivity.md +++ b/docs/misc/collations-and-case-sensitivity.md @@ -42,18 +42,25 @@ This will cause all textual operators on this column to be case-insensitive. ### Database collation -PostgreSQL also allows you to specify collations at the database level, when it is created. While this will eventually allow specifying that all columns and operations are case-insensitive, for example, PostgreSQL currently does not support non-deterministic collations at the database level. To work around this limitation, the EF Core provider has a feature which allows you to specify the `default column collation` at the model level, and the provider will ensure it is automatically specified on all columns: +PostgreSQL also allows you to specify collations at the database level, when it is created: ```c# protected override void OnModelCreating(ModelBuilder modelBuilder) { - modelBuilder.HasCollation("my_collation", locale: "en-u-ks-primary", provider: "icu", deterministic: false); + modelBuilder.HasCollation(""); +} +``` - builder.UseDefaultColumnCollation("my_collation"); +Unfortunately, the database collation is quote limited in PostgreSQL; it notably does not support non-deterministic collations (e.g. case-insensitive ones). To work around this limitation, you can use EF Core's [pre-convention model configuration](https://docs.microsoft.com/ef/core/modeling/bulk-configuration#pre-convention-configuration) feature: + +```c# +protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder) +{ + configurationBuilder.Properties().UseCollation("my_collation"); } ``` -All columns created after this directive is added will automatically have their collation specified accordingly, and all existing columns will be altered. The end result of the above is very similar to specifying a database collation: instead of telling PostgreSQL to implicit apply a collation to all columns, the EF Core provider does the same. +All columns created with this configuration will automatically have their collation specified accordingly, and all existing columns will be altered. The end result of the above is very similar to specifying a database collation: instead of telling PostgreSQL to implicit apply a collation to all columns, EF Core will do the same for you in its migrations. ## The citext type diff --git a/docs/release-notes/7.0.md b/docs/release-notes/7.0.md new file mode 100644 index 0000000000..edc2faca37 --- /dev/null +++ b/docs/release-notes/7.0.md @@ -0,0 +1,29 @@ +# 7.0 Release Notes + +## New features + +## Breaking changes + +### Obsoleted default column collations + +Versions 6.0 and below had a mechanism that allowed defining a "default column collation", which is applied individually to every text column by default; this differed from the database collation, which is applied once to the database at creation time. This mechanism was introduced because in PostgreSQL, the database collation is quite limited, and for example does not allow specifying non-deterministic collations (e.g. case-insensitive ones). + +However, with the introduction of [pre-convention model configuration](https://docs.microsoft.com/ef/core/modeling/bulk-configuration#pre-convention-configuration) in EF Core, it's now possible to use that generic mechanism for specifying the default collation. As a result, the Npgsql-specific mechanism has been obsoleted and will be removed in a future version. + +Default column collations involve the following code: + +```c# +protected override void OnModelCreating(ModelBuilder modelBuilder) +{ + modelBuilder.UseDefaultColumnCollation(""); +} +``` + +To switch to the standard EF Core API, replace the code above with the following: + +```c# +protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder) +{ + configurationBuilder.Properties().UseCollation(""); +} +``` From e39bcf935c1ee76c458358fbf3d00cc28d72a6f7 Mon Sep 17 00:00:00 2001 From: Ignas Maslinskas <5737899+Hoffs@users.noreply.github.com> Date: Thu, 28 Apr 2022 12:16:13 +0300 Subject: [PATCH 104/207] Update enum docs to mention add support (#204) Co-authored-by: Shay Rojansky --- docs/mapping/enum.md | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/docs/mapping/enum.md b/docs/mapping/enum.md index 2c1b9b0bd6..b6ce37f7a5 100644 --- a/docs/mapping/enum.md +++ b/docs/mapping/enum.md @@ -19,12 +19,12 @@ protected override void OnModelCreating(ModelBuilder builder) ```c# protected override void OnModelCreating(ModelBuilder builder) - => builder.HasPostgresEnum("Mood", new[] { "happy", "sad" }); + => builder.HasPostgresEnum("mood", new[] { "happy", "sad" }); ``` --- -This causes the EF Core provider to create your data enum type, `Mood`, with two labels: `happy` and `sad`. This will cause the appropriate migration to be created. +This causes the EF Core provider to create your enum type, `mood`, with two labels: `happy` and `sad`. This will cause the appropriate migration to be created. If you are using `context.Database.Migrate()` to create your enums, you need to instruct Npgsql to reload all types after applying your migrations: @@ -47,7 +47,7 @@ static MyDbContext() => NpgsqlConnection.GlobalTypeMapper.MapEnum(); ``` -This code lets Npgsql know that your CLR enum type, `Mood`, should be mapped to a database enum called `Mood`. Note that if your enum is in a custom schema (not `public`), you must specify that schema in the call to `MapEnum`. +This code lets Npgsql know that your CLR enum type, `Mood`, should be mapped to a database enum called `mood`. Note that if your enum is in a custom schema (not `public`), you must specify that schema in the call to `MapEnum`. If you're curious as to inner workings, this code maps the enum with the ADO.NET provider - [see here for the full docs](http://www.npgsql.org/doc/types/enums_and_composites.html). When the Npgsql EF Core first initializes, it calls into the ADO.NET provider to get all mapped enums, and sets everything up internally at the EF Core layer as well. @@ -75,10 +75,16 @@ using (var ctx = new MyDbContext()) ## Altering enum definitions -Although PostgreSQL allows [altering enum types](https://www.postgresql.org/docs/current/static/sql-altertype.html), the Npgsql provider currently does not generate SQL for those operations (beyond creating and dropping the entire type). If you to add or rename enum values (removal is not supported by PostgreSQL), you'll have to include raw SQL in your migrations (this is quite easy to do). As always, test your migrations carefully before running them on production databases. +The Npgsql provider only allow adding new values to existing enums, and the appropriate migrations will be automatically created as you add values to your CLR enum type. However, PostgreSQL itself doesn't support removing enum values (since these may be in use), and while renaming values is supported, it isn't automatically done by the provider to avoid using unreliable detection heuristics. Renaming an enum value can be done by including [raw SQL](https://docs.microsoft.com/en-us/ef/core/managing-schemas/migrations/managing?tabs=dotnet-core-cli#arbitrary-changes-via-raw-sql) in your migrations as follows: + +```c# +migrationBuilder.Sql(@"ALTER TYPE mood RENAME VALUE happy TO thrilled;"); +``` + +As always, test your migrations carefully before running them on production databases. ## Scaffolding from an existing database -If you're creating your model from an existing database, the provider will recognize enums in your database, and scaffold the appropriate `HasPostgresEnum()` lines in your model. However, since the scaffolding process has no knowledge of your CLR type, and will therefore skip your enum columns (warnings will be logged). You will have to create the CLR type, add the global mapping and add the properties to your entities. +If you're creating your model from an existing database, the provider will recognize enums in your database, and scaffold the appropriate `HasPostgresEnum()` lines in your model. However, the scaffolding process has no knowledge of your CLR type, and will therefore skip your enum columns (warnings will be logged). You will have to create the CLR type, add the global mapping and add the properties to your entities. In the future it may be possible to scaffold the actual enum type (and with it the properties), but this doesn't happen at the moment. From bbe473b08dca37998899d9552fe797daffaefa67 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Sun, 8 May 2022 12:25:41 +0200 Subject: [PATCH 105/207] Some general tweaks and fixes (#206) --- docs/mapping/translations.md | 172 +++++++++++++------------- docs/misc/other.md | 12 +- docs/modeling/generated-properties.md | 8 +- 3 files changed, 90 insertions(+), 102 deletions(-) diff --git a/docs/mapping/translations.md b/docs/mapping/translations.md index 50316970cd..0234e342b4 100644 --- a/docs/mapping/translations.md +++ b/docs/mapping/translations.md @@ -4,22 +4,53 @@ Entity Framework Core allows providers to translate query expressions to SQL for The Npgsql-specific translations are listed below. Some areas, such as [full-text search](full-text-search.md), have their own pages in this section which list additional translations. -## Binary functions +## String functions -.NET | SQL | Notes ----------------------------- | ------------------------------- | -------- -bytes[i] | get_byte(bytes, i) | Added in 5.0 -bytes.Contains(value) | position(value IN bytes) > 0 | Added in 5.0 -bytes.Length | length(@bytes) | Added in 5.0 -bytes1.SequenceEqual(bytes2) | @bytes = @second | Added in 5.0 +.NET | SQL | Notes +------------------------------------------------------------- | ------------------------------------------------------ | -------- +EF.Functions.Collate(operand, collation) | operand COLLATE collation | Added in 5.0 +EF.Functions.Like(matchExpression, pattern) | matchExpression LIKE pattern +EF.Functions.Like(matchExpression, pattern, escapeCharacter) | matchExpression LIKE pattern ESCAPE escapeCharacter +EF.Functions.ILike(matchExpression, pattern) | [matchExpression ILIKE pattern](../misc/collations-and-case-sensitivity.md) +EF.Functions.ILike(matchExpression, pattern, escapeCharacter) | [matchExpression ILIKE pattern ESCAPE escapeCharacter](../misc/collations-and-case-sensitivity.md) +string.Compare(strA, strB) | CASE WHEN strA = strB THEN 0 ... END +string.Concat(str0, str1) | str0 \|\| str1 +string.IsNullOrEmpty(value) | value IS NULL OR value = '' +string.IsNullOrWhiteSpace(value) | value IS NULL OR btrim(value, E' \t\n\r') = '' +stringValue.CompareTo(strB) | CASE WHEN stringValue = strB THEN 0 ... END +stringValue.Contains(value) | strpos(stringValue, value) > 0 +stringValue.EndsWith(value) | stringValue LIKE '%' \|\| value +stringValue.FirstOrDefault() | substr(stringValue, 1, 1) | Added in 5.0 +stringValue.IndexOf(value) | strpos(stringValue, value) - 1 +stringValue.LastOrDefault() | substr(stringValue, length(stringValue), 1) | Added in 5.0 +stringValue.Length | length(stringValue) +stringValue.PadLeft(length) | lpad(stringValue, length) +stringValue.PadLeft(length, char) | lpad(stringValue, length, char) +stringValue.PadRight(length) | rpad(stringValue, length) +stringValue.PadRight(length, char) | rpad(stringValue, length, char) +stringValue.Replace(oldValue, newValue) | replace(stringValue, oldValue, newValue) +stringValue.StartsWith(value) | stringValue LIKE value \|\| '%' +stringValue.Substring(startIndex, length) | substr(stringValue, startIndex + 1, @length) +stringValue.ToLower() | lower(stringValue) +stringValue.ToUpper() | upper(stringValue) +stringValue.Trim() | btrim(stringValue) +stringValue.Trim(trimChar) | btrim(stringValue, trimChar) +stringValue.TrimEnd() | rtrim(stringValue) +stringValue.TrimEnd(trimChar) | rtrim(stringValue, trimChar) +stringValue.TrimStart() | ltrim(stringValue) +stringValue.TrimStart(trimChar) | ltrim(stringValue, trimChar) +EF.Functions.Reverse(value) | reverse(value) +Regex.IsMatch(stringValue, "^A+") | [stringValue ~ '^A+'](http://www.postgresql.org/docs/current/static/functions-matching.html#FUNCTIONS-POSIX-REGEXP) (with options) +Regex.IsMatch(stringValue, "^A+", regexOptions) | [stringValue ~ '^A+'](http://www.postgresql.org/docs/current/static/functions-matching.html#FUNCTIONS-POSIX-REGEXP) (with options) ## Date and time functions > [!NOTE] > Some of the operations below depend on the concept of a "local time zone" (e.g. `DateTime.Today`). While in .NET this is the machine time zone where .NET is running, the corresponding PostgreSQL translations use the [`TimeZone`](https://www.postgresql.org/docs/current/runtime-config-client.html#GUC-TIMEZONE) connection parameter as the local time zone. - -> [!NOTE] +> > Since version 6.0, many of the below DateTime translations are also supported on DateTimeOffset. +> +> See also Npgsql's [NodaTime support](/efcore/mapping/nodatime.html), which is a better and safer way of interacting with date/time data. .NET | SQL | Notes ----------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- | -------- @@ -69,8 +100,51 @@ new DateTime(year, month, day) | [make_date(y new DateTime(y, m, d, h, m, s) | [make_timestamp(y, m, d, h, m, s)](https://www.postgresql.org/docs/current/functions-datetime.html) | new DateTime(y, m, d, h, m, s, kind) | [make_timestamp or make_timestamptz](https://www.postgresql.org/docs/current/functions-datetime.html), based on `kind` | Added in 6.0 -> [!NOTE] -> See also Npgsql's [NodaTime support](/efcore/mapping/nodatime.html). +## Miscellaneous functions + +.NET | SQL +---------------------------------------- | -------------------- +collection.Contains(item) | item IN collection +enumValue.HasFlag(flag) | enumValue & flag = flag +Guid.NewGuid() | [uuid_generate_v4()](https://www.postgresql.org/docs/current/uuid-ossp.html), or [gen_random_uuid()](https://www.postgresql.org/docs/current/functions-uuid.html) on PostgreSQL 13 with EF Core 5 and above. +nullable.GetValueOrDefault() | coalesce(nullable, 0) +nullable.GetValueOrDefault(defaultValue) | coalesce(nullable, defaultValue) + +## Binary functions + +.NET | SQL | Notes +---------------------------- | ------------------------------- | -------- +bytes[i] | get_byte(bytes, i) | Added in 5.0 +bytes.Contains(value) | position(value IN bytes) > 0 | Added in 5.0 +bytes.Length | length(@bytes) | Added in 5.0 +bytes1.SequenceEqual(bytes2) | @bytes = @second | Added in 5.0 + +## Math functions + +.NET | SQL | Notes +----------------------- | ------------------ | ----- +Math.Abs(value) | abs(value) | +Math.Acos(d) | acos(d) | +Math.Asin(d) | asin(d) | +Math.Atan(d) | atan(d) | +Math.Atan2(y, x) | atan2(y, x) | +Math.Ceiling(d) | ceiling(d) | +Math.Cos(d) | cos(d) | +Math.Exp(d) | exp(d) | +Math.Floor(d) | floor(d) | +Math.Log(d) | ln(d) | +Math.Log10(d) | log(d) | +Math.Max(x, y) | greatest(x, y) | +Math.Min(x, y) | least(x, y) | +Math.Pow(x, y) | power(x, y) | +Math.Round(d) | round(d) | +Math.Round(d, decimals) | round(d, decimals) | +Math.Sin(a) | sin(a) | +Math.Sign(value) | sign(value)::int | +Math.Sqrt(d) | sqrt(d) | +Math.Tan(a) | tan(a) | +Math.Truncate(d) | trunc(d) | +EF.Functions.Random() | random() | Added in 6.0 ## Network functions @@ -108,72 +182,6 @@ EF.Functions.Merge(inet1, inet2) | [inet_merge(inet1, inet2)](ht EF.Functions.Truncate(macaddr) | [trunc(macaddr)](https://www.postgresql.org/docs/current/functions-net.html#CIDR-INET-FUNCTIONS-TABLE) EF.Functions.Set7BitMac8(macaddr8) | [macaddr8_set7bit(macaddr8)](https://www.postgresql.org/docs/current/functions-net.html#CIDR-INET-FUNCTIONS-TABLE) -## Numeric functions - -.NET | SQL | Notes ------------------------ | ------------------ | ----- -Math.Abs(value) | abs(value) | -Math.Acos(d) | acos(d) | -Math.Asin(d) | asin(d) | -Math.Atan(d) | atan(d) | -Math.Atan2(y, x) | atan2(y, x) | -Math.Ceiling(d) | ceiling(d) | -Math.Cos(d) | cos(d) | -Math.Exp(d) | exp(d) | -Math.Floor(d) | floor(d) | -Math.Log(d) | ln(d) | -Math.Log10(d) | log(d) | -Math.Max(x, y) | greatest(x, y) | -Math.Min(x, y) | least(x, y) | -Math.Pow(x, y) | power(x, y) | -Math.Round(d) | round(d) | -Math.Round(d, decimals) | round(d, decimals) | -Math.Sin(a) | sin(a) | -Math.Sign(value) | sign(value)::int | -Math.Sqrt(d) | sqrt(d) | -Math.Tan(a) | tan(a) | -Math.Truncate(d) | trunc(d) | -EF.Functions.Random() | random() | Added in 6.0 - -## String functions - -.NET | SQL | Notes -------------------------------------------------------------- | ------------------------------------------------------ | -------- -EF.Functions.Collate(operand, collation) | operand COLLATE collation | Added in 5.0 -EF.Functions.Like(matchExpression, pattern) | matchExpression LIKE pattern -EF.Functions.Like(matchExpression, pattern, escapeCharacter) | matchExpression LIKE pattern ESCAPE escapeCharacter -EF.Functions.ILike(matchExpression, pattern) | [matchExpression ILIKE pattern](../misc/collations-and-case-sensitivity.md) -EF.Functions.ILike(matchExpression, pattern, escapeCharacter) | [matchExpression ILIKE pattern ESCAPE escapeCharacter](../misc/collations-and-case-sensitivity.md) -string.Compare(strA, strB) | CASE WHEN strA = strB THEN 0 ... END -string.Concat(str0, str1) | str0 \|\| str1 -string.IsNullOrEmpty(value) | value IS NULL OR value = '' -string.IsNullOrWhiteSpace(value) | value IS NULL OR btrim(value, E' \t\n\r') = '' -stringValue.CompareTo(strB) | CASE WHEN stringValue = strB THEN 0 ... END -stringValue.Contains(value) | strpos(stringValue, value) > 0 -stringValue.EndsWith(value) | stringValue LIKE '%' \|\| value -stringValue.FirstOrDefault() | substr(stringValue, 1, 1) | Added in 5.0 -stringValue.IndexOf(value) | strpos(stringValue, value) - 1 -stringValue.LastOrDefault() | substr(stringValue, length(stringValue), 1) | Added in 5.0 -stringValue.Length | length(stringValue) -stringValue.PadLeft(length) | lpad(stringValue, length) -stringValue.PadLeft(length, char) | lpad(stringValue, length, char) -stringValue.PadRight(length) | rpad(stringValue, length) -stringValue.PadRight(length, char) | rpad(stringValue, length, char) -stringValue.Replace(oldValue, newValue) | replace(stringValue, oldValue, newValue) -stringValue.StartsWith(value) | stringValue LIKE value \|\| '%' -stringValue.Substring(startIndex, length) | substr(stringValue, startIndex + 1, @length) -stringValue.ToLower() | lower(stringValue) -stringValue.ToUpper() | upper(stringValue) -stringValue.Trim() | btrim(stringValue) -stringValue.Trim(trimChar) | btrim(stringValue, trimChar) -stringValue.TrimEnd() | rtrim(stringValue) -stringValue.TrimEnd(trimChar) | rtrim(stringValue, trimChar) -stringValue.TrimStart() | ltrim(stringValue) -stringValue.TrimStart(trimChar) | ltrim(stringValue, trimChar) -EF.Functions.Reverse(value) | reverse(value) -Regex.IsMatch(stringValue, "^A+") | [stringValue ~ '^A+'](http://www.postgresql.org/docs/current/static/functions-matching.html#FUNCTIONS-POSIX-REGEXP) (with options) -Regex.IsMatch(stringValue, "^A+", regexOptions) | [stringValue ~ '^A+'](http://www.postgresql.org/docs/current/static/functions-matching.html#FUNCTIONS-POSIX-REGEXP) (with options) - ## Trigram functions The below translations provide functionality for determining the similarity of alphanumeric text based on trigram matching, using the [`pg_trgm`](https://www.postgresql.org/docs/current/pgtrgm.html) extension which is bundled with standard PostgreSQL distributions. All the below parameters are strings. @@ -228,13 +236,3 @@ ltree.NLevel | nlevel(ltree ltree.Index(subpath) | index(ltree, subpath) ltree.Index(subpath, 2) | index(ltree, subpath, 2) LTree.LongestCommonAncestor(ltree1, ltree2) | lca(index(ltree1, ltree2) - -## Miscellaneous functions - -.NET | SQL ----------------------------------------- | -------------------- -collection.Contains(item) | item IN collection -enumValue.HasFlag(flag) | enumValue & flag = flag -Guid.NewGuid() | [uuid_generate_v4()](https://www.postgresql.org/docs/current/uuid-ossp.html), or [gen_random_uuid()](https://www.postgresql.org/docs/current/functions-uuid.html) on PostgreSQL 13 with EF Core 5 and above. -nullable.GetValueOrDefault() | coalesce(nullable, 0) -nullable.GetValueOrDefault(defaultValue) | coalesce(nullable, defaultValue) diff --git a/docs/misc/other.md b/docs/misc/other.md index 21fbcea228..eb43450c0d 100644 --- a/docs/misc/other.md +++ b/docs/misc/other.md @@ -12,7 +12,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) ## Execution Strategy -Since 2.0.0, the Npgsql EF Core provider provides a retrying execution strategy, which will attempt to detect most transient PostgreSQL/network errors and will automatically retry your operation. To enable, place the following code in your context's `OnModelConfiguring`: +The Npgsql EF Core provider provides a retrying execution strategy, which will attempt to detect most transient PostgreSQL/network errors and will automatically retry your operation. To enable, place the following code in your context's `OnModelConfiguring`: ```c# protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) @@ -45,16 +45,6 @@ You may also consider passing `Trust Server Certificate=true` in your connection > [!CAUTION] > When specifying the options via `OnConfiguring`, make sure that the callbacks you pass in are static methods. Passing in instance methods causes EF Core to create a new service provider for each context instance, which can degrade performance in a significant way. -## Comments - -PostgreSQL allows you to [attach comments](https://www.postgresql.org/docs/current/static/sql-syntax-lexical.html#SQL-SYNTAX-COMMENTS) to database objects, which can help explain their purpose for someone examining the schema. The Npgsql EF Core provider supports this for tables or columns, simply set the comment in your model's `OnModelCreating` as follows: - -```c# -protected override void OnModelCreating(ModelBuilder modelBuilder) - => modelBuilder.Entity() - .HasComment("Some comment"); -``` - ## CockroachDB Interleave In Parent If you're using CockroachDB, the Npgsql EF Core provider exposes its ["interleave in parent" feature](https://www.cockroachlabs.com/docs/stable/interleave-in-parent.html). Use the following code: diff --git a/docs/modeling/generated-properties.md b/docs/modeling/generated-properties.md index ce3559962b..fd43b5eb3a 100644 --- a/docs/modeling/generated-properties.md +++ b/docs/modeling/generated-properties.md @@ -174,9 +174,9 @@ CREATE TRIGGER "UpdateTimestamp" > [!NOTE] > This feature works only on PostgreSQL 12 or above, and was introduced in version 3.0.0 of the provider. -PostgreSQL 12 added support for [stored generated columns](https://www.postgresql.org/docs/current/ddl-generated-columns.html), and Npgsql feature supports that feature as well. The following configuration: +PostgreSQL 12 added support for [stored generated columns](https://www.postgresql.org/docs/current/ddl-generated-columns.html), and Npgsql feature supports that feature as well: -### [Version 5.0](#tab/efcore5.0) +### [Version 5.0](#tab/efcore5) ```c# protected override void OnModelCreating(ModelBuilder modelBuilder) @@ -187,7 +187,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) } ``` -### [Version 3.x](#tab/efcore3.x) +### [Version 3.x](#tab/efcore3) ```c# protected override void OnModelCreating(ModelBuilder modelBuilder) @@ -200,7 +200,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) *** -Will cause the following migration SQL to be generated +This will cause the following migration SQL to be generated: ```sql ALTER TABLE ""Person"" ADD ""DisplayName"" text GENERATED ALWAYS AS (""FirstName"" || ' ' || ""LastName"") STORED; From fe2cf931173c1b740bb1c26b5c64826f87a02729 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Tue, 17 May 2022 11:49:13 +0200 Subject: [PATCH 106/207] Add note on wrapping scalars for JSON functions See https://github.com/npgsql/efcore.pg/issues/2363 --- docs/mapping/json.md | 46 +++++++++++++++++++++++--------------------- 1 file changed, 24 insertions(+), 22 deletions(-) diff --git a/docs/mapping/json.md b/docs/mapping/json.md index e4f201253b..f6fa866dbc 100644 --- a/docs/mapping/json.md +++ b/docs/mapping/json.md @@ -201,34 +201,36 @@ The following expression types and functions are translated: ### [POCO Mapping](#tab/poco) -.NET | SQL -----------------------------------------------------------------------------|----- -customer.Name | [customer->>'Name'](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-OP-TABLE) -customer.Orders[1].Price | [customer#>>'{Orders,0,Price}'[1]](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-OP-TABLE) -customer.Orders.Length | [jsonb_array_length(customer->'Orders')](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-PROCESSING-TABLE) -EF.Functions.JsonContains(customer, @"{""Name"": ""Joe"", ""Age"": 25}") | [customer @> '{"Name": "Joe", "Age": 25}'](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) -EF.Functions.JsonContained(@"{""Name"": ""Joe"", ""Age"": 25}", e.Customer) | ['{"Name": "Joe", "Age": 25}' <@ customer](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) -EF.Functions.JsonExists(e.Customer, "Age") | [customer ? 'Age'](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) -EF.Functions.JsonExistsAny(e.Customer, "Age", "Address") | [customer ?\| ARRAY['Age','Address']](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) -EF.Functions.JsonExistsAll(e.Customer, "Age", "Address") | [customer ?& ARRAY['Age','Address']](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) -EF.Functions.JsonTypeof(e.Customer.Age) | [jsonb_typeof(customer->'Age')](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-PROCESSING-TABLE) +.NET | SQL +--------------------------------------------------------------------------------------- | ---- +customer.Name | [customer->>'Name'](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-OP-TABLE) +customer.Orders[1].Price | [customer#>>'{Orders,0,Price}'[1]](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-OP-TABLE) +customer.Orders.Length | [jsonb_array_length(customer->'Orders')](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-PROCESSING-TABLE) +EF.Functions.JsonContains(customer, @"{""Name"": ""Joe"", ""Age"": 25}")1 | [customer @> '{"Name": "Joe", "Age": 25}'](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) +EF.Functions.JsonContained(@"{""Name"": ""Joe"", ""Age"": 25}", e.Customer)1 | ['{"Name": "Joe", "Age": 25}' <@ customer](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) +EF.Functions.JsonExists(e.Customer, "Age") | [customer ? 'Age'](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) +EF.Functions.JsonExistsAny(e.Customer, "Age", "Address") | [customer ?\| ARRAY['Age','Address']](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) +EF.Functions.JsonExistsAll(e.Customer, "Age", "Address") | [customer ?& ARRAY['Age','Address']](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) +EF.Functions.JsonTypeof(e.Customer.Age) | [jsonb_typeof(customer->'Age')](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-PROCESSING-TABLE) ### [JsonDocument Mapping](#tab/jsondocument) -.NET | SQL -------------------------------------------------------------------------------|----- -customer.RootElement.GetProperty("Name").GetString() | [customer->>'Name' = 'Joe'](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-OP-TABLE) -customer.RootElement.GetProperty("Orders")[1].GetProperty("Price").GetInt32() | [customer#>>'{Orders,0,Price}'[1] = 8](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-OP-TABLE) -customer.RootElement.GetProperty("Orders").GetArrayLength() | [jsonb_array_length(customer->'Orders'](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-PROCESSING-TABLE) -EF.Functions.JsonContains(customer, @"{""Name"": ""Joe"", ""Age"": 25}") | [customer @> '{"Name": "Joe", "Age": 25}'](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) -EF.Functions.JsonContained(@"{""Name"": ""Joe"", ""Age"": 25}", customer) | ['{"Name": "Joe", "Age": 25}' <@ customer](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) -EF.Functions.JsonExists(customer, "Age") | [customer ? 'Age'](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) -EF.Functions.JsonExistsAny(customer, "Age", "Address") | [customer ?\| ARRAY['Age','Address']](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) -EF.Functions.JsonExistsAll(customer, "Age", "Address") | [customer ?& ARRAY['Age','Address']](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) -EF.Functions.JsonTypeof(customer.GetProperty("Age")) == "number" | [jsonb_typeof(customer->'Age') = 'number'](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-PROCESSING-TABLE) +.NET | SQL +------------------------------------------------------------------------------------- | ---- +customer.RootElement.GetProperty("Name").GetString() | [customer->>'Name' = 'Joe'](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-OP-TABLE) +customer.RootElement.GetProperty("Orders")[1].GetProperty("Price").GetInt32() | [customer#>>'{Orders,0,Price}'[1] = 8](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-OP-TABLE) +customer.RootElement.GetProperty("Orders").GetArrayLength() | [jsonb_array_length(customer->'Orders'](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-PROCESSING-TABLE) +EF.Functions.JsonContains(customer, @"{""Name"": ""Joe"", ""Age"": 25}")1 | [customer @> '{"Name": "Joe", "Age": 25}'](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) +EF.Functions.JsonContained(@"{""Name"": ""Joe"", ""Age"": 25}", customer)1 | ['{"Name": "Joe", "Age": 25}' <@ customer](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) +EF.Functions.JsonExists(customer, "Age") | [customer ? 'Age'](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) +EF.Functions.JsonExistsAny(customer, "Age", "Address") | [customer ?\| ARRAY['Age','Address']](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) +EF.Functions.JsonExistsAll(customer, "Age", "Address") | [customer ?& ARRAY['Age','Address']](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) +EF.Functions.JsonTypeof(customer.GetProperty("Age")) == "number" | [jsonb_typeof(customer->'Age') = 'number'](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-PROCESSING-TABLE) *** +1 JSON functions which accept a .NET object require a JSON document, and do not accept scalar values. For example, to pass a scalar to `JsonContains`, wrap it in a `JsonElement`. + ## Indexing JSON columns > [!NOTE] From 92bffbb7a3a90db208327cfcc46712a0ab73f929 Mon Sep 17 00:00:00 2001 From: Nino Floris Date: Thu, 19 May 2022 18:25:12 +0200 Subject: [PATCH 107/207] Improve scalar wrapping note (#210) In particular adding an example for root level JSON strings --- docs/mapping/json.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/mapping/json.md b/docs/mapping/json.md index f6fa866dbc..65a69273dc 100644 --- a/docs/mapping/json.md +++ b/docs/mapping/json.md @@ -229,7 +229,7 @@ EF.Functions.JsonTypeof(customer.GetProperty("Age")) == "number" *** -1 JSON functions which accept a .NET object require a JSON document, and do not accept scalar values. For example, to pass a scalar to `JsonContains`, wrap it in a `JsonElement`. +1 JSON functions which accept a .NET object will not accept .NET scalar values. For example, to pass a scalar to `JsonContains` wrap it in a `JsonElement` or alternatively wrap it in a string. Note: a root level JSON string value requires quotes and escaping `@"""Joe"""`, just as any nested JSON string value would. ## Indexing JSON columns From 7a1c7690112b30694670a50e8755b4593fe58d6e Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Tue, 24 May 2022 09:57:49 +0200 Subject: [PATCH 108/207] Add JSON List.Count translation note See https://github.com/npgsql/efcore.pg/issues/2374 --- docs/mapping/json.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/mapping/json.md b/docs/mapping/json.md index 65a69273dc..62cd0a6642 100644 --- a/docs/mapping/json.md +++ b/docs/mapping/json.md @@ -205,7 +205,7 @@ The following expression types and functions are translated: --------------------------------------------------------------------------------------- | ---- customer.Name | [customer->>'Name'](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-OP-TABLE) customer.Orders[1].Price | [customer#>>'{Orders,0,Price}'[1]](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-OP-TABLE) -customer.Orders.Length | [jsonb_array_length(customer->'Orders')](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-PROCESSING-TABLE) +customer.Orders.Length (or Count) | [jsonb_array_length(customer->'Orders')](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-PROCESSING-TABLE) EF.Functions.JsonContains(customer, @"{""Name"": ""Joe"", ""Age"": 25}")1 | [customer @> '{"Name": "Joe", "Age": 25}'](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) EF.Functions.JsonContained(@"{""Name"": ""Joe"", ""Age"": 25}", e.Customer)1 | ['{"Name": "Joe", "Age": 25}' <@ customer](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) EF.Functions.JsonExists(e.Customer, "Age") | [customer ? 'Age'](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) From 76c1de28abc8b4671edcd24c6e2f7a957d126776 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Tue, 24 May 2022 15:17:13 +0200 Subject: [PATCH 109/207] Add note on mapping enums with multiple context types See https://github.com/npgsql/efcore.pg/issues/2263 --- docs/mapping/enum.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/docs/mapping/enum.md b/docs/mapping/enum.md index b6ce37f7a5..4ffe90d32f 100644 --- a/docs/mapping/enum.md +++ b/docs/mapping/enum.md @@ -51,6 +51,9 @@ This code lets Npgsql know that your CLR enum type, `Mood`, should be mapped to If you're curious as to inner workings, this code maps the enum with the ADO.NET provider - [see here for the full docs](http://www.npgsql.org/doc/types/enums_and_composites.html). When the Npgsql EF Core first initializes, it calls into the ADO.NET provider to get all mapped enums, and sets everything up internally at the EF Core layer as well. +> [!NOTE] +> If you have multiple context types, all `MapEnum` invocations must be done before *any* of them is used; this means that the code cannot be in your static constructors, but must be moved to the program start. + ## Using enum properties Once your enum is mapped and created in the database, you can use your CLR enum type just like any other property: From 78e56ddaa2931a17b822e8b83f8bef7e0a1e10b0 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Thu, 30 Jun 2022 13:10:55 +0300 Subject: [PATCH 110/207] Correct GUID generation docs (#218) --- docs/modeling/generated-properties.md | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/docs/modeling/generated-properties.md b/docs/modeling/generated-properties.md index fd43b5eb3a..4663393f30 100644 --- a/docs/modeling/generated-properties.md +++ b/docs/modeling/generated-properties.md @@ -100,11 +100,11 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) => modelBuilder.UseHiLo(); ``` -## Guid/UUID Generation +## GUID/UUID Generation -By default, for Guid key properties (or if you specify `ValueGeneratedOnAdd` on any Guid property), a random `Guid` value will be generated client-side and sent to the database. +By default, for GUID key properties, a random GUID is generated client-side by the EF provider and sent to the database. -If you prefer to generate values in the database instead, you can do so by specifying `HasDefaultValueSql` on your property, and call the function to generate the `Guid` in the SQL expression. Which function to use depends on your PostgreSQL version: +If you prefer to generate values in the database instead, you can do so by specifying `HasDefaultValueSql` on your property, and call the function to generate the value in the SQL expression. Which function to use depends on your PostgreSQL version: ### [PG 13+](#tab/13) @@ -120,7 +120,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) ### [Older](#tab/older) -Versions of PostgreSQL prior to 13 don't include any Guid/UUID generation functions, but extensions such as `uuid-ossp` or `pgcrypto` exist to fill thie gap. This can be done by placing the following code in your model's `OnModelCreating`: +Versions of PostgreSQL prior to 13 don't include any GUID/UUID generation functions, but extensions such as `uuid-ossp` or `pgcrypto` exist to fill thie gap. This can be done by placing the following code in your model's `OnModelCreating`: ```c# protected override void OnModelCreating(ModelBuilder modelBuilder) @@ -138,6 +138,9 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) See [the PostgreSQL docs on UUID for more details](https://www.postgresql.org/docs/current/static/datatype-uuid.html). +> [!NOTE] +> Generating `Guid` values in the database causes an additional network roundtrip when a principal and a dependent are inserted in the same `SaveChanges`, as the principal's key needs to be fetched before inserting the dependent's. + ## Timestamp generation In many scenarios, it's useful to have a column containing the timestamp when the row was originally created. To do this, add a `DateTime` property to your entity type (or `Instant` if using NodaTime) , and configure its default with `HasDefaultValueSql` as follows: From 6eb0878e2590046e3312741c52c25fe8896995bb Mon Sep 17 00:00:00 2001 From: Arad Alvand Date: Wed, 27 Jul 2022 23:04:12 +0430 Subject: [PATCH 111/207] Put quotes around enum labels in the ALTER TYPE statement (#227) --- docs/mapping/enum.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/mapping/enum.md b/docs/mapping/enum.md index 4ffe90d32f..b177a49d40 100644 --- a/docs/mapping/enum.md +++ b/docs/mapping/enum.md @@ -81,7 +81,7 @@ using (var ctx = new MyDbContext()) The Npgsql provider only allow adding new values to existing enums, and the appropriate migrations will be automatically created as you add values to your CLR enum type. However, PostgreSQL itself doesn't support removing enum values (since these may be in use), and while renaming values is supported, it isn't automatically done by the provider to avoid using unreliable detection heuristics. Renaming an enum value can be done by including [raw SQL](https://docs.microsoft.com/en-us/ef/core/managing-schemas/migrations/managing?tabs=dotnet-core-cli#arbitrary-changes-via-raw-sql) in your migrations as follows: ```c# -migrationBuilder.Sql(@"ALTER TYPE mood RENAME VALUE happy TO thrilled;"); +migrationBuilder.Sql(@"ALTER TYPE mood RENAME VALUE 'happy' TO 'thrilled';"); ``` As always, test your migrations carefully before running them on production databases. From 9daa4b719a6065f6291ffa796fa2f8a778b6b315 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Wed, 24 Aug 2022 21:51:38 +0300 Subject: [PATCH 112/207] Add note on 6.0 timestamp migration and seeding (#230) --- docs/release-notes/6.0.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/docs/release-notes/6.0.md b/docs/release-notes/6.0.md index c5d3f0ebff..ee9aee910a 100644 --- a/docs/release-notes/6.0.md +++ b/docs/release-notes/6.0.md @@ -115,6 +115,16 @@ This will ensure that no time zone conversions will be applied when converting t 2020-01-01 14:00:00+02 | timestamp with time zone ``` +#### Changing timestamp seed data + +When switching from `timestamp without time zone` to `timezone with time zone`, you may have have non-UTC timestamp literals in your seeding configuration: + +```c# +modelBuilder.Entity().HasData(new Blog { Id = 1, Timestamp = new DateTime(2020, 1, 1, 0, 0, 0) }); +``` + +If so, you'll have to change these to be UTC. In addition, all migrations code since the change must be modified in the same way, to only seed UTC DateTime into the column; the model snapshot should be changed as well. + #### Opting out of the new timestamp mapping logic The changes described above are far-reaching, and may break applications in various ways. You can upgrade to version 6.0 but opt out of the new mapping by enabling the `Npgsql.EnableLegacyTimestampBehavior` [AppContext switch](https://docs.microsoft.com/en-us/dotnet/api/system.appcontext?view=net-5.0). To do this and revert to the legacy timestamp behavior, add the following to your context's constructor, before any Npgsql or EF Core operations are invoked: From 41cf05c85cc784bc2a2b107ebfb1a67d39d75849 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Sun, 8 May 2022 12:27:21 +0200 Subject: [PATCH 113/207] Document row value comparisons See https://github.com/npgsql/efcore.pg/issues/2349 --- docs/mapping/translations.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/docs/mapping/translations.md b/docs/mapping/translations.md index 0234e342b4..169a21a0bd 100644 --- a/docs/mapping/translations.md +++ b/docs/mapping/translations.md @@ -146,6 +146,22 @@ Math.Tan(a) | tan(a) | Math.Truncate(d) | trunc(d) | EF.Functions.Random() | random() | Added in 6.0 +## Row value comparisons + +The following allow expressing [comparisons over SQL row values](https://www.postgresql.org/docs/current/functions-comparisons.html#ROW-WISE-COMPARISON). This are particularly useful for implementing efficient pagination, see [the EF Core docs](https://docs.microsoft.com/ef/core/querying/pagination) for more information. + +> [!NOTE] +> All of the below are being introduced in version 7.0 of the provider. + +.NET | SQL +--------------------------------------------------------------------------------- | ---------------- +EF.Functions.GreaterThan(ValueTuple.Create(a, b), ValueTuple.Create(c, d)) | (a, b) > (c, d) +EF.Functions.LessThan(ValueTuple.Create(a, b), ValueTuple.Create(c, d)) | (a, b) < (c, d) +EF.Functions.GreaterThanOrEqual(ValueTuple.Create(a, b), ValueTuple.Create(c, d)) | (a, b) >= (c, d) +EF.Functions.LessThanOrEqual(ValueTuple.Create(a, b), ValueTuple.Create(c, d)) | (a, b) <= (c, d) +ValueTuple.Create(a, b).Equals(ValueTuple.Create(c, d)) | (a, b) = (c, d) +!ValueTuple.Create(a, b).Equals(ValueTuple.Create(c, d)) | (a, b) <> (c, d) + ## Network functions .NET | SQL From af1d387cc00aa7d3f19a0d60edeb153d9f0f16de Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Tue, 17 May 2022 14:26:30 +0200 Subject: [PATCH 114/207] Document tsvector computed columns over JSON data See https://github.com/npgsql/efcore.pg/pull/2224 --- docs/mapping/full-text-search.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/docs/mapping/full-text-search.md b/docs/mapping/full-text-search.md index d66041acf2..a1c10bccbf 100644 --- a/docs/mapping/full-text-search.md +++ b/docs/mapping/full-text-search.md @@ -146,6 +146,12 @@ var npgsql = context.Products .ToList(); ``` +## Computed column over JSON columns + +Starting with 7.0, the provider can also create computed `tsvector` columns over JSON columns. Simply use `HasGeneratedTsVectorColumn()` as shown above, and when applied to JSON columns, the provider will automatically generate [`json_to_tsvector/jsonb_to_tsvector`](https://www.postgresql.org/docs/current/functions-textsearch.html#TEXTSEARCH-FUNCTIONS-TABLE) as appropriate. + +Note that this will pass the filter `all` to these functions, meaning that all values in the JSON document will be included. To customize the filter - or to create the computed column on older versions of the provider - simply specify the function yourself via [`HasComputedColumnSql`](https://docs.microsoft.com/ef/core/modeling/generated-properties?tabs=data-annotations#computed-columns). + ## Operation translation Almost all PostgreSQL full text search functions can be called through LINQ queries. All supported EF Core LINQ methods are defined in extension classes in the `Microsoft.EntityFrameworkCore` namespace, so simply referencing the Npgsql provider will light up these methods. The following table lists all supported operations; if an operation you need is missing, please open an issue to request for it. From 156268328b8f471df116f1b4fcff2c8579f66158 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Sun, 5 Jun 2022 11:49:26 +0200 Subject: [PATCH 115/207] Document aggregate function translations --- docs/mapping/array.md | 1 + docs/mapping/nodatime.md | 4 ++ docs/mapping/nts.md | 4 ++ docs/mapping/translations.md | 77 +++++++++++++++++++++++++++++++++--- docs/release-notes/7.0.md | 12 ++++++ 5 files changed, 93 insertions(+), 5 deletions(-) diff --git a/docs/mapping/array.md b/docs/mapping/array.md index 505eb14e3b..db9945f8c2 100644 --- a/docs/mapping/array.md +++ b/docs/mapping/array.md @@ -45,3 +45,4 @@ array.Any(s => EF.Functions.Like(string, s)) | [string LIKE ANY (array)](https: array.Any(s => EF.Functions.ILike(string, s)) | [string ILIKE ANY (array)](https://www.postgresql.org/docs/current/functions-comparisons.html#id-1.5.8.30.16) | array.All(s => EF.Functions.Like(string, s)) | [string LIKE ALL (array)](https://www.postgresql.org/docs/current/functions-comparisons.html#id-1.5.8.30.16) | array.All(s => EF.Functions.ILike(string, s)) | [string ILIKE ALL (array)](https://www.postgresql.org/docs/current/functions-comparisons.html#id-1.5.8.30.16) | +EF.Functions.ArrayAgg(values) | [array_agg(values)](https://www.postgresql.org/docs/current/functions-aggregate.html#FUNCTIONS-AGGREGATE-TABLE) | Added in 7.0, See [Aggregate functions](#aggregate-functions). diff --git a/docs/mapping/nodatime.md b/docs/mapping/nodatime.md index 64b62d7aae..397f6334c9 100644 --- a/docs/mapping/nodatime.md +++ b/docs/mapping/nodatime.md @@ -95,5 +95,9 @@ LocalDateTime.InZoneLeniently(DateTimeZoneProviders.Tzdb["Europe/Berlin"]).ToIns ZonedDateTime.ToInstant | No PG operation (.NET-side conversion from ZonedDateTime to Instant only) | Added in 6.0 Instant.InUtc | No PG operation (.NET-side conversion from Instant to ZonedDateTime only) | Added in 6.0 Instant.ToDateTimeUtc | No PG operation (.NET-side conversion from Instant to UTC DateTime only) | Added in 6.0 +EF.Functions.Sum(periods) | [sum(periods)](https://www.postgresql.org/docs/current/functions-aggregate.html#FUNCTIONS-AGGREGATE-TABLE) | Added in 7.0, see [Aggregate functions](translations.md#aggregate-functions). +EF.Functions.Sum(durations) | [sum(durations)](https://www.postgresql.org/docs/current/functions-aggregate.html#FUNCTIONS-AGGREGATE-TABLE) | Added in 7.0, see [Aggregate functions](translations.md#aggregate-functions). +EF.Functions.Average(periods) | [avg(durations)](https://www.postgresql.org/docs/current/functions-aggregate.html#FUNCTIONS-AGGREGATE-TABLE) | Added in 7.0, see [Aggregate functions](translations.md#aggregate-functions). +EF.Functions.Average(durations) | [avg(durations)](https://www.postgresql.org/docs/current/functions-aggregate.html#FUNCTIONS-AGGREGATE-TABLE) | Added in 7.0, see [Aggregate functions](translations.md#aggregate-functions). In addition to the above, most arithmetic operators are also translated (e.g. LocalDate + Period). diff --git a/docs/mapping/nts.md b/docs/mapping/nts.md index 900a12c739..5f033d2f05 100644 --- a/docs/mapping/nts.md +++ b/docs/mapping/nts.md @@ -149,3 +149,7 @@ point.M | [ST_M(point)] point.X | [ST_X(point)](https://postgis.net/docs/ST_X.html) point.Y | [ST_Y(point)](https://postgis.net/docs/ST_Y.html) point.Z | [ST_Z(point)](https://postgis.net/docs/ST_Z.html) +UnaryUnionOp.Union(geometries) | [ST_Union(geometries)](https://postgis.net/docs/ST_Union.html) | Added in 7.0, see [Aggregate functions](translations.md#aggregate-functions). +GeometryCombiner.Combine(geometries) | [ST_Collect(geometries)](https://postgis.net/docs/ST_Collect.html) | Added in 7.0, see [Aggregate functions](translations.md#aggregate-functions). +EnvelopeCombiner.CombineAsGeometry(geometries) | [ST_Extent(geometries)::geometry](https://postgis.net/docs/ST_Extent.html) | Added in 7.0, see [Aggregate functions](translations.md#aggregate-functions). +ConvexHull.Create(geometries) | [ST_ConvexHull(geometries)](https://postgis.net/docs/ST_ConvexHull.html) | Added in 7.0, see [Aggregate functions](translations.md#aggregate-functions). diff --git a/docs/mapping/translations.md b/docs/mapping/translations.md index 169a21a0bd..f866e47fc7 100644 --- a/docs/mapping/translations.md +++ b/docs/mapping/translations.md @@ -6,9 +6,9 @@ The Npgsql-specific translations are listed below. Some areas, such as [full-tex ## String functions -.NET | SQL | Notes -------------------------------------------------------------- | ------------------------------------------------------ | -------- -EF.Functions.Collate(operand, collation) | operand COLLATE collation | Added in 5.0 +.NET | SQL | Notes +------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- | -------- +EF.Functions.Collate(operand, collation) | operand COLLATE collation | Added in 5.0 EF.Functions.Like(matchExpression, pattern) | matchExpression LIKE pattern EF.Functions.Like(matchExpression, pattern, escapeCharacter) | matchExpression LIKE pattern ESCAPE escapeCharacter EF.Functions.ILike(matchExpression, pattern) | [matchExpression ILIKE pattern](../misc/collations-and-case-sensitivity.md) @@ -20,9 +20,9 @@ string.IsNullOrWhiteSpace(value) | value IS NULL OR stringValue.CompareTo(strB) | CASE WHEN stringValue = strB THEN 0 ... END stringValue.Contains(value) | strpos(stringValue, value) > 0 stringValue.EndsWith(value) | stringValue LIKE '%' \|\| value -stringValue.FirstOrDefault() | substr(stringValue, 1, 1) | Added in 5.0 +stringValue.FirstOrDefault() | substr(stringValue, 1, 1) | Added in 5.0 stringValue.IndexOf(value) | strpos(stringValue, value) - 1 -stringValue.LastOrDefault() | substr(stringValue, length(stringValue), 1) | Added in 5.0 +stringValue.LastOrDefault() | substr(stringValue, length(stringValue), 1) | Added in 5.0 stringValue.Length | length(stringValue) stringValue.PadLeft(length) | lpad(stringValue, length) stringValue.PadLeft(length, char) | lpad(stringValue, length, char) @@ -42,6 +42,7 @@ stringValue.TrimStart(trimChar) | ltrim(stringValu EF.Functions.Reverse(value) | reverse(value) Regex.IsMatch(stringValue, "^A+") | [stringValue ~ '^A+'](http://www.postgresql.org/docs/current/static/functions-matching.html#FUNCTIONS-POSIX-REGEXP) (with options) Regex.IsMatch(stringValue, "^A+", regexOptions) | [stringValue ~ '^A+'](http://www.postgresql.org/docs/current/static/functions-matching.html#FUNCTIONS-POSIX-REGEXP) (with options) +string.Join(", ", strings)1 | [string_agg(strings, ', ')](https://www.postgresql.org/docs/current/functions-aggregate.html#FUNCTIONS-AGGREGATE-TABLE) | Added in 7.0, see [Aggregate functions](#aggregate-functions). ## Date and time functions @@ -99,6 +100,8 @@ DateTime.SpecifyKind(nonUtcDateTime, DateTimeKind.Utc) | [nonUtcDateT new DateTime(year, month, day) | [make_date(year, month, day)](https://www.postgresql.org/docs/current/functions-datetime.html) | new DateTime(y, m, d, h, m, s) | [make_timestamp(y, m, d, h, m, s)](https://www.postgresql.org/docs/current/functions-datetime.html) | new DateTime(y, m, d, h, m, s, kind) | [make_timestamp or make_timestamptz](https://www.postgresql.org/docs/current/functions-datetime.html), based on `kind` | Added in 6.0 +EF.Functions.Sum(timespans) | [sum(timespans)](https://www.postgresql.org/docs/current/functions-aggregate.html#FUNCTIONS-AGGREGATE-TABLE) | Added in 7.0, see [Aggregate functions](#aggregate-functions). +EF.Functions.Average(timespans) | [avg(timespans)](https://www.postgresql.org/docs/current/functions-aggregate.html#FUNCTIONS-AGGREGATE-TABLE) | Added in 7.0, see [Aggregate functions](#aggregate-functions). ## Miscellaneous functions @@ -146,6 +149,8 @@ Math.Tan(a) | tan(a) | Math.Truncate(d) | trunc(d) | EF.Functions.Random() | random() | Added in 6.0 +See also [Aggregate statistics functions](#aggregate-statistics-functions). + ## Row value comparisons The following allow expressing [comparisons over SQL row values](https://www.postgresql.org/docs/current/functions-comparisons.html#ROW-WISE-COMPARISON). This are particularly useful for implementing efficient pagination, see [the EF Core docs](https://docs.microsoft.com/ef/core/querying/pagination) for more information. @@ -252,3 +257,65 @@ ltree.NLevel | nlevel(ltree ltree.Index(subpath) | index(ltree, subpath) ltree.Index(subpath, 2) | index(ltree, subpath, 2) LTree.LongestCommonAncestor(ltree1, ltree2) | lca(index(ltree1, ltree2) + +## Aggregate functions + +The PostgreSQL aggregate functions are documented [here](https://www.postgresql.org/docs/current/functions-aggregate.html). + +> [!NOTE] +> All the below aggregate functions were added in version 7.0. + +| .NET | SQL +| ---------------------------------------------------------------------------------- | -------------------- +| string.Join(", ", strings) | string_agg(strings, ', ') +| EF.Functions.ArrayAgg(values) | array_agg(values) +| EF.Functions.JsonbAgg(values) | jsonb_agg(values) +| EF.Functions.JsonAgg(values) | json_agg(values) +| EF.Functions.RangeAgg(ranges) | range_agg(ranges) +| EF.Functions.RangeIntersectAgg(ranges) | range_intersect_agg(ranges) +| EF.Functions.Sum(timespans) | sum(timespans) +| EF.Functions.Average(timespans) | avg(timespans) +| EF.Functions.JsonObjectAgg(tuple_of_2) | json_object_agg(tuple_of_2.first, tuple_of_2.second) +| | +| EF.Functions.StandardDeviationSample(values) | stddev_samp(values) +| EF.Functions.StandardDeviationPopulation(values) | stddev_pop(values) +| EF.Functions.VarianceSample(values) | var_samp(values) +| EF.Functions.VariancePopulation(values) | var_pop(values) +| | +| EF.Functions.Correlation(tuple) | corr(tuple_of_2.first, tuple_of_2.second) +| EF.Functions.CovariancePopulation(tuple) | covar_pop(tuple_of_2.first, tuple_of_2.second) +| EF.Functions.CovarianceSample(tuple) | covar_samp(tuple_of_2.first, tuple_of_2.second) +| EF.Functions.RegrAverageX(tuple) | regr_avgx(tuple_of_2.first, tuple_of_2.second) +| EF.Functions.RegrAverageY(tuple) | regr_avgy(tuple_of_2.first, tuple_of_2.second) +| EF.Functions.RegrCount(tuple) | regr_count(tuple_of_2.first, tuple_of_2.second) +| EF.Functions.RegrIntercept(tuple) | regr_intercept(tuple_of_2.first, tuple_of_2.second) +| EF.Functions.RegrR2(tuple) | regr_r2(tuple_of_2.first, tuple_of_2.second) +| EF.Functions.RegrSlope(tuple) | regr_slope(tuple_of_2.first, tuple_of_2.second) +| EF.Functions.RegrSXX(tuple) | regr_sxx(tuple_of_2.first, tuple_of_2.second) +| EF.Functions.RegrSXY(tuple) | regr_sxy(tuple_of_2.first, tuple_of_2.second) + +Aggregate functions can be used as follows: + +```c# +var query = ctx.Set() + .GroupBy(c => c.City) + .Select( + g => new + { + City = g.Key, + Companies = EF.Functions.ArrayAgg(g.Select(c => c.ContactName)) + }); +``` + +To use functions accepting a tuple_of_2, project out from the group as follows: + +```c# +var query = ctx.Set() + .GroupBy(c => c.City) + .Select( + g => new + { + City = g.Key, + Companies = EF.Functions.JsonObjectAgg(g.Select(c => ValueTuple.Create(c.CompanyName, c.ContactName))) + }); +``` diff --git a/docs/release-notes/7.0.md b/docs/release-notes/7.0.md index edc2faca37..e0862a68f7 100644 --- a/docs/release-notes/7.0.md +++ b/docs/release-notes/7.0.md @@ -2,6 +2,18 @@ ## New features +### Extensive support for aggregate function translation + +EF Core 7.0 added support for translating provider-specific aggregate functions, and EFCore.PG builds on top of that to translate most major aggregate functions that PostgreSQL supports. This unlocks support for: + +* string_agg: pack a column's values into a single string, with or without a delimiter. +* array_agg: pack a column's values into a PostgreSQL array. This can help with efficient fetching of dependent values, avoiding the so-called "cartesian explosion" problem. +* Statistical functions: standard deviation, variance and many others. +* Spatial functions: ST_Union, ST_Collect, ST_Extent and ST_ConvexHull. +* JSON functions: load values from the database as JSON documents with json_agg/jsonb_agg and json_object_agg/jsonb_object_agg. + +For the PostgreSQL documentation on aggregate functions, see [this page](https://www.postgresql.org/docs/current/functions-aggregate.html). The exact translations supported by the provider are documented in the [translations page](../mapping/translations.md#aggregate-functions). + ## Breaking changes ### Obsoleted default column collations From 1fbab8d1ff6cd94c8a11bea768fdd010a94b81b9 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Thu, 25 Aug 2022 19:20:43 +0300 Subject: [PATCH 116/207] Correct range aggregate translation docs (#232) --- docs/mapping/range.md | 3 +++ docs/mapping/translations.md | 5 +++-- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/docs/mapping/range.md b/docs/mapping/range.md index fdaae37036..93cdbab8f4 100644 --- a/docs/mapping/range.md +++ b/docs/mapping/range.md @@ -97,3 +97,6 @@ range1.Intersect(range2) | [range1 * range2](https://www.postgresql range1.Except(range2) | [range1 - range2](https://www.postgresql.org/docs/current/static/functions-range.html#RANGE-OPERATORS-TABLE) range1.Merge(range2) | [range_merge(range1, range2)](https://www.postgresql.org/docs/current/functions-range.html#RANGE-FUNCTIONS-TABLE) multirange.Merge() | [range_merge(multirange)](https://www.postgresql.org/docs/current/functions-range.html#MULTIRANGE-FUNCTIONS-TABLE) +ranges.RangeAgg() | [range_agg(ranges)](https://www.postgresql.org/docs/current/functions-aggregate.html) +ranges.RangeIntersectAgg() | [range_intersect_agg(ranges)](https://www.postgresql.org/docs/current/functions-aggregate.html) +multiranges.RangeIntersectAgg() | [range_intersect_agg(multiranges)](https://www.postgresql.org/docs/current/functions-aggregate.html) | Added in 7.0, See [Aggregate functions](#aggregate-functions). diff --git a/docs/mapping/translations.md b/docs/mapping/translations.md index f866e47fc7..2da22eb1c1 100644 --- a/docs/mapping/translations.md +++ b/docs/mapping/translations.md @@ -271,11 +271,12 @@ The PostgreSQL aggregate functions are documented [here](https://www.postgresql. | EF.Functions.ArrayAgg(values) | array_agg(values) | EF.Functions.JsonbAgg(values) | jsonb_agg(values) | EF.Functions.JsonAgg(values) | json_agg(values) -| EF.Functions.RangeAgg(ranges) | range_agg(ranges) -| EF.Functions.RangeIntersectAgg(ranges) | range_intersect_agg(ranges) | EF.Functions.Sum(timespans) | sum(timespans) | EF.Functions.Average(timespans) | avg(timespans) | EF.Functions.JsonObjectAgg(tuple_of_2) | json_object_agg(tuple_of_2.first, tuple_of_2.second) +| ranges.RangeAgg() | range_agg(ranges) +| ranges.RangeIntersectAgg() | range_intersect_agg(ranges) +| multiranges.RangeIntersectAgg() | range_intersect_agg(multiranges) | | | EF.Functions.StandardDeviationSample(values) | stddev_samp(values) | EF.Functions.StandardDeviationPopulation(values) | stddev_pop(values) From b5d02408bee027e38acd55eaa20e980ded56d703 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Thu, 20 Oct 2022 10:42:03 +0200 Subject: [PATCH 117/207] Pack of 7.0 doc changes --- docs/mapping/json.md | 6 ++--- docs/mapping/translations.md | 6 +++-- docs/modeling/concurrency.md | 45 +++++++++++++++++++++++++++++------- docs/modeling/indexes.md | 38 ++++++++++++++++++++---------- docs/release-notes/7.0.md | 18 +++++++++++++++ 5 files changed, 88 insertions(+), 25 deletions(-) diff --git a/docs/mapping/json.md b/docs/mapping/json.md index 62cd0a6642..f065bd7ac4 100644 --- a/docs/mapping/json.md +++ b/docs/mapping/json.md @@ -1,5 +1,8 @@ # JSON Mapping +> [!NOTE] +> EF Core 7.0 introduced support for [JSON columns](https://learn.microsoft.com/ef/core/what-is-new/ef-core-7.0/whatsnew#json-columns). Npgsql's JSON support - detailed below - is different, and has been available since version 3.0. We plan to adopt EF's JSON support in version 8.0. + PostgreSQL has rich, built-in support for storing JSON columns and efficiently performing complex queries operations on them. Newcomers can read more about the PostgreSQL support on [the JSON types page](https://www.postgresql.org/docs/current/datatype-json.html), and on the [functions and operators page](https://www.postgresql.org/docs/current/functions-json.html). Note that the below mapping mechanisms support both the `jsonb` and `json` types, although the former is almost always preferred for efficiency reasons. The Npgsql EF Core provider allows you to map PostgreSQL JSON columns in three different ways: @@ -8,9 +11,6 @@ The Npgsql EF Core provider allows you to map PostgreSQL JSON columns in three d 2. As strongly-typed user-defined types (POCOs) 3. As [System.Text.Json](https://devblogs.microsoft.com/dotnet/try-the-new-system-text-json-apis/) DOM types (JsonDocument or JsonElement) -> [!NOTE] -> Mapping to POCO or to System.Text.Json types was introduced in version 3.0.0 - ## String mapping The simplest form of mapping to JSON is via a regular string property, just like an ordinary text column: diff --git a/docs/mapping/translations.md b/docs/mapping/translations.md index 2da22eb1c1..b485f2459c 100644 --- a/docs/mapping/translations.md +++ b/docs/mapping/translations.md @@ -42,7 +42,9 @@ stringValue.TrimStart(trimChar) | ltrim(stringValu EF.Functions.Reverse(value) | reverse(value) Regex.IsMatch(stringValue, "^A+") | [stringValue ~ '^A+'](http://www.postgresql.org/docs/current/static/functions-matching.html#FUNCTIONS-POSIX-REGEXP) (with options) Regex.IsMatch(stringValue, "^A+", regexOptions) | [stringValue ~ '^A+'](http://www.postgresql.org/docs/current/static/functions-matching.html#FUNCTIONS-POSIX-REGEXP) (with options) -string.Join(", ", strings)1 | [string_agg(strings, ', ')](https://www.postgresql.org/docs/current/functions-aggregate.html#FUNCTIONS-AGGREGATE-TABLE) | Added in 7.0, see [Aggregate functions](#aggregate-functions). +string.Join(", ", a, b) | [concat_ws(', ', a, b)](https://www.postgresql.org/docs/current/functions-string.html#FUNCTIONS-STRING-OTHER) | Added in 7.0 (previously array_to_string) +string.Join(", ", array) | [array_to_string(array, ', ', '')](https://www.postgresql.org/docs/current/functions-array.html#ARRAY-FUNCTIONS-TABLE) +string.Join(", ", agg_strings) | [string_agg(agg_strings, ', ')](https://www.postgresql.org/docs/current/functions-aggregate.html#FUNCTIONS-AGGREGATE-TABLE) | Added in 7.0, see [Aggregate functions](#aggregate-functions). ## Date and time functions @@ -267,7 +269,7 @@ The PostgreSQL aggregate functions are documented [here](https://www.postgresql. | .NET | SQL | ---------------------------------------------------------------------------------- | -------------------- -| string.Join(", ", strings) | string_agg(strings, ', ') +| string.Join(", ", agg_strings) | string_agg(agg_strings, ', ') | EF.Functions.ArrayAgg(values) | array_agg(values) | EF.Functions.JsonbAgg(values) | jsonb_agg(values) | EF.Functions.JsonAgg(values) | json_agg(values) diff --git a/docs/modeling/concurrency.md b/docs/modeling/concurrency.md index 32045c0a4b..62ed2163e6 100644 --- a/docs/modeling/concurrency.md +++ b/docs/modeling/concurrency.md @@ -9,20 +9,49 @@ Entity Framework Core supports the concept of optimistic concurrency - a propert Although applications can update concurrency tokens themselves, we frequently rely on the database automatically updating a column on update - a "last modified" timestamp, an SQL Server `rowversion`, etc. Unfortunately PostgreSQL doesn't have such auto-updating columns - but there is one feature that can be used for concurrency token. All PostgreSQL tables have a set of [implicit and hidden system columns](https://www.postgresql.org/docs/current/ddl-system-columns.html), among which `xmin` holds the ID of the latest updating transaction. Since this value automatically gets updated every time the row is changed, it is ideal for use as a concurrency token. -To enable this feature on an entity, insert the following code into your context's `OnModelCreating` method: +Starting with version 7.0, you can map a `uint` property to the PostgreSQL `xmin` system column using the standard EF Core mechanisms: + +### [Data Annotations](#tab/data-annotations) ```c# -protected override void OnModelCreating(ModelBuilder modelBuilder) - => modelBuilder.Entity() - .UseXminAsConcurrencyToken(); +public class SomeEntity +{ + public int Id { get; set; } + + [Timestamp] + public uint Version { get; set; } +} +``` + +### [Fluent API](#tab/fluent-api) + +```c# +class MyContext : DbContext +{ + public DbSet SomeEntities { get; set; } + + protected override void OnModelCreating(ModelBuilder modelBuilder) + { + modelBuilder.Entity() + .Property(b => b.Version) + .IsRowVersion(); + } +} + +public class SomeEntity +{ + public int Id { get; set; } + public uint Version { get; set; } +} ``` -Note that by default, this will set up a [shadow property](https://docs.microsoft.com/ef/core/modeling/shadow-properties) called `xmin` on your entity. This means that when you load an entity from the database, the value of `xmin` will be stored in the context, making it [impossible to use that instance with another context](https://stackoverflow.com/a/60871156) (without reloading the entity). If you plan to pass instances between different contexts, consider adding an `xmin` property of type `uint` on your entity; this will automatically cause the concurrency token to be stored on the instance instead: +*** + +In older version of the provider, use the following instead: ```c# -class Blog +protected override void OnModelCreating(ModelBuilder modelBuilder) { - ... - public uint xmin { get; set; } + modelBuilder.Entity().UseXminAsConcurrencyToken(); } ``` diff --git a/docs/modeling/indexes.md b/docs/modeling/indexes.md index b478856d11..5dbf90faa8 100644 --- a/docs/modeling/indexes.md +++ b/docs/modeling/indexes.md @@ -2,15 +2,15 @@ PostgreSQL and the Npgsql provider support the standard index modeling described in [the EF Core docs](https://docs.microsoft.com/ef/core/modeling/indexes). This page describes some supported PostgreSQL-specific features. -## PostgreSQL covering indexes (INCLUDE) +## Covering indexes (INCLUDE) -Since version 11, PostgreSQL supports [covering indexes](https://paquier.xyz/postgresql-2/postgres-11-covering-indexes), which allow you to include "non-key" columns in your indexes. This allows you to perform index-only scans and can provide a significant performance boost: +PostgreSQL supports [covering indexes](https://paquier.xyz/postgresql-2/postgres-11-covering-indexes), which allow you to include "non-key" columns in your indexes. This allows you to perform index-only scans and can provide a significant performance boost: ```c# protected override void OnModelCreating(ModelBuilder modelBuilder) => modelBuilder.Entity() - .HasIndex(b => b.Id) - .IncludeProperties(b => b.Name); + .HasIndex(b => b.Id) + .IncludeProperties(b => b.Name); ``` This will create an index for searching on `Id`, but containing also the column `Name`, so that reading the latter will not involve accessing the table. The SQL generated is as follows: @@ -19,7 +19,21 @@ This will create an index for searching on `Id`, but containing also the column CREATE INDEX "IX_Blog_Id" ON blogs ("Id") INCLUDE ("Name"); ``` -## PostgreSQL index methods +## Treating nulls as non-distinct + +> [!NOTE] +> This feature was introduced in version 7.0, and is available starting with PostgreSQL 15. + +By default, when you create a unique index, PostgreSQL treats null values as distinct; this means that a unique index can contain multiple null values in a column. When creating an index, you can also instruct PostgreSQL that nulls should be treated as *non-distinct*; this causes a unique constraint violation to be raised if a column contains multiple null values: + +```c# +protected override void OnModelCreating(ModelBuilder modelBuilder) + => modelBuilder.Entity() + .IsUnique() + .AreNullsDistinct(false); +``` + +## Index methods PostgreSQL supports a number of *index methods*, or *types*. These are specified at index creation time via the `USING ` clause, see the [PostgreSQL docs for `CREATE INDEX`](https://www.postgresql.org/docs/current/static/sql-createindex.html) and [this page](https://www.postgresql.org/docs/current/static/indexes-types.html) for information on the different types. @@ -28,19 +42,19 @@ The Npgsql EF Core provider allows you to specify the index method to be used by ```c# protected override void OnModelCreating(ModelBuilder modelBuilder) => modelBuilder.Entity() - .HasIndex(b => b.Url) - .HasMethod("gin"); + .HasIndex(b => b.Url) + .HasMethod("gin"); ``` -## PostgreSQL index operator classes +## Index operator classes PostgreSQL allows you to specify [operator classes on your indexes](https://www.postgresql.org/docs/current/indexes-opclass.html), to allow tweaking how the index should work. Use the following code to specify an operator class: ```c# protected override void OnConfiguring(DbContextOptionsBuilder builder) => modelBuilder.Entity() - .HasIndex(b => new { b.Id, b.Name }) - .HasOperators(null, "text_pattern_ops"); + .HasIndex(b => new { b.Id, b.Name }) + .HasOperators(null, "text_pattern_ops"); ``` Note that each operator class is used for the corresponding index column, by order. In the example above, the `text_pattern_ops` class will be used for the `Name` column, while the `Id` column will use the default class (unspecified), producing the following SQL: @@ -58,8 +72,8 @@ The EF provider allows you to specify that an index should be created *concurren ```c# protected override void OnModelCreating(ModelBuilder modelBuilder) => modelBuilder.Entity() - .HasIndex(b => b.Url) - .IsCreatedConcurrently(); + .HasIndex(b => b.Url) + .IsCreatedConcurrently(); ``` > [!CAUTION] diff --git a/docs/release-notes/7.0.md b/docs/release-notes/7.0.md index e0862a68f7..6b9e71a887 100644 --- a/docs/release-notes/7.0.md +++ b/docs/release-notes/7.0.md @@ -2,6 +2,12 @@ ## New features +### ExecuteUpdate and ExecuteDelete + +Support has been added for the new EF Core 7.0 `ExecuteUpdate` and `ExecuteDelete`, which allow expressing arbitrary, efficient updates via LINQ. See the EF [What's new section](https://learn.microsoft.com/ef/core/what-is-new/ef-core-7.0/whatsnew#executeupdate-and-executedelete-bulk-updates) for documentation. + +### Basic support for DbDataSource + ### Extensive support for aggregate function translation EF Core 7.0 added support for translating provider-specific aggregate functions, and EFCore.PG builds on top of that to translate most major aggregate functions that PostgreSQL supports. This unlocks support for: @@ -14,6 +20,14 @@ EF Core 7.0 added support for translating provider-specific aggregate functions, For the PostgreSQL documentation on aggregate functions, see [this page](https://www.postgresql.org/docs/current/functions-aggregate.html). The exact translations supported by the provider are documented in the [translations page](../mapping/translations.md#aggregate-functions). +### Row value expressions + +### Other new features + +* Support for PostgreSQL 15 non-distinct NULLs in unique indexes, causing unique constraint violations if a column contains multiple null values. [See the documentation for more details](../modeling/indexes.md#treating-nulls-as-non-distinct). +* Stored procedure mappings: PostgreSQL support has been added for *stored procedure mapping*, which is a new feature in EF Core 7.0. See the EF [What's new section](https://learn.microsoft.com/ef/core/what-is-new/ef-core-7.0/whatsnew#stored-procedure-mapping) for documentation. Note that PostgreSQL 14 or above is required to use this feature (for output parameters). + + ## Breaking changes ### Obsoleted default column collations @@ -39,3 +53,7 @@ protected override void ConfigureConventions(ModelConfigurationBuilder configura configurationBuilder.Properties().UseCollation(""); } ``` + +### Obsoleted UseXminAsConcurrencyToken + +Starting with version 7.0, concurrency token properties can be configured via the standard EF means, rather than the PostgreSQL-specific `UseXminAsConcurrencyToken`; simply configure any `uint` property with the `IsRowVersion()` Fluent API or the `[Timestamp]` Data Annotation. [See the documentation for more details](../modeling/concurrency.md). \ No newline at end of file From 897724b13584f7923ede12d0ff6fa278148c9b19 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Sun, 30 Oct 2022 20:59:32 +0200 Subject: [PATCH 118/207] Markdownlint fixes --- docs/release-notes/7.0.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/docs/release-notes/7.0.md b/docs/release-notes/7.0.md index 6b9e71a887..c16e0fb17d 100644 --- a/docs/release-notes/7.0.md +++ b/docs/release-notes/7.0.md @@ -27,7 +27,6 @@ For the PostgreSQL documentation on aggregate functions, see [this page](https:/ * Support for PostgreSQL 15 non-distinct NULLs in unique indexes, causing unique constraint violations if a column contains multiple null values. [See the documentation for more details](../modeling/indexes.md#treating-nulls-as-non-distinct). * Stored procedure mappings: PostgreSQL support has been added for *stored procedure mapping*, which is a new feature in EF Core 7.0. See the EF [What's new section](https://learn.microsoft.com/ef/core/what-is-new/ef-core-7.0/whatsnew#stored-procedure-mapping) for documentation. Note that PostgreSQL 14 or above is required to use this feature (for output parameters). - ## Breaking changes ### Obsoleted default column collations @@ -56,4 +55,4 @@ protected override void ConfigureConventions(ModelConfigurationBuilder configura ### Obsoleted UseXminAsConcurrencyToken -Starting with version 7.0, concurrency token properties can be configured via the standard EF means, rather than the PostgreSQL-specific `UseXminAsConcurrencyToken`; simply configure any `uint` property with the `IsRowVersion()` Fluent API or the `[Timestamp]` Data Annotation. [See the documentation for more details](../modeling/concurrency.md). \ No newline at end of file +Starting with version 7.0, concurrency token properties can be configured via the standard EF means, rather than the PostgreSQL-specific `UseXminAsConcurrencyToken`; simply configure any `uint` property with the `IsRowVersion()` Fluent API or the `[Timestamp]` Data Annotation. [See the documentation for more details](../modeling/concurrency.md). From 3569342aa72a6ab4218334613d51ec692dec3e68 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Wed, 2 Nov 2022 08:43:20 +0200 Subject: [PATCH 119/207] Document the new Microsoft.Extensions.Logging support (#255) Closes #166 --- docs/release-notes/7.0.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/release-notes/7.0.md b/docs/release-notes/7.0.md index c16e0fb17d..4af9efd2e4 100644 --- a/docs/release-notes/7.0.md +++ b/docs/release-notes/7.0.md @@ -6,7 +6,9 @@ Support has been added for the new EF Core 7.0 `ExecuteUpdate` and `ExecuteDelete`, which allow expressing arbitrary, efficient updates via LINQ. See the EF [What's new section](https://learn.microsoft.com/ef/core/what-is-new/ef-core-7.0/whatsnew#executeupdate-and-executedelete-bulk-updates) for documentation. -### Basic support for DbDataSource +### Support for DbDataSource + +* Fully standardized logging via Microsoft.Extensions.Logging, including a new [Npgsql.DependencyInjection](https://learn.microsoft.com/en-us/dotnet/core/extensions/logging?tabs=command-line) ### Extensive support for aggregate function translation From 955c087d142c71b92eeee7551ef8d4b711b911e1 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Thu, 3 Nov 2022 18:03:53 +0200 Subject: [PATCH 120/207] Document NpgsqlDataSource (#256) * 7.0 release notes * Basic usage * Enum and composite mapping * Plugin pages * Authentication page Closes #215 --- docs/release-notes/7.0.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/docs/release-notes/7.0.md b/docs/release-notes/7.0.md index 4af9efd2e4..cb039773ce 100644 --- a/docs/release-notes/7.0.md +++ b/docs/release-notes/7.0.md @@ -8,8 +8,6 @@ Support has been added for the new EF Core 7.0 `ExecuteUpdate` and `ExecuteDelet ### Support for DbDataSource -* Fully standardized logging via Microsoft.Extensions.Logging, including a new [Npgsql.DependencyInjection](https://learn.microsoft.com/en-us/dotnet/core/extensions/logging?tabs=command-line) - ### Extensive support for aggregate function translation EF Core 7.0 added support for translating provider-specific aggregate functions, and EFCore.PG builds on top of that to translate most major aggregate functions that PostgreSQL supports. This unlocks support for: From 1a0c0e323604b9475d9403713456dfb8a6d1fa0d Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Thu, 3 Nov 2022 18:04:29 +0200 Subject: [PATCH 121/207] Document NpgsqlDataSource (#256) * 7.0 release notes * Basic usage * Enum and composite mapping * Plugin pages * Authentication page Closes #215 From 3184390d972f04bbbfee284a2f3cd19c7819eaa8 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Wed, 9 Nov 2022 22:36:04 +0200 Subject: [PATCH 122/207] Placeholders for EFCore.PG 7.0 release notes --- docs/release-notes/7.0.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/release-notes/7.0.md b/docs/release-notes/7.0.md index cb039773ce..0185d56ab8 100644 --- a/docs/release-notes/7.0.md +++ b/docs/release-notes/7.0.md @@ -8,6 +8,8 @@ Support has been added for the new EF Core 7.0 `ExecuteUpdate` and `ExecuteDelet ### Support for DbDataSource +TO BE COMPLETED + ### Extensive support for aggregate function translation EF Core 7.0 added support for translating provider-specific aggregate functions, and EFCore.PG builds on top of that to translate most major aggregate functions that PostgreSQL supports. This unlocks support for: @@ -22,6 +24,8 @@ For the PostgreSQL documentation on aggregate functions, see [this page](https:/ ### Row value expressions +TO BE COMPLETED + ### Other new features * Support for PostgreSQL 15 non-distinct NULLs in unique indexes, causing unique constraint violations if a column contains multiple null values. [See the documentation for more details](../modeling/indexes.md#treating-nulls-as-non-distinct). From 4aea15b0901fab2bccf255a937be87df1403638b Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Thu, 10 Nov 2022 12:17:26 +0200 Subject: [PATCH 123/207] Complete EFCore.PG 7.0 release notes --- docs/mapping/translations.md | 2 +- docs/release-notes/7.0.md | 61 +++++++++++++++++++++++++++++------- 2 files changed, 51 insertions(+), 12 deletions(-) diff --git a/docs/mapping/translations.md b/docs/mapping/translations.md index b485f2459c..fbb9c86fbc 100644 --- a/docs/mapping/translations.md +++ b/docs/mapping/translations.md @@ -158,7 +158,7 @@ See also [Aggregate statistics functions](#aggregate-statistics-functions). The following allow expressing [comparisons over SQL row values](https://www.postgresql.org/docs/current/functions-comparisons.html#ROW-WISE-COMPARISON). This are particularly useful for implementing efficient pagination, see [the EF Core docs](https://docs.microsoft.com/ef/core/querying/pagination) for more information. > [!NOTE] -> All of the below are being introduced in version 7.0 of the provider. +> All of the below were introduced in version 7.0 of the provider. .NET | SQL --------------------------------------------------------------------------------- | ---------------- diff --git a/docs/release-notes/7.0.md b/docs/release-notes/7.0.md index 0185d56ab8..0360d10618 100644 --- a/docs/release-notes/7.0.md +++ b/docs/release-notes/7.0.md @@ -8,23 +8,62 @@ Support has been added for the new EF Core 7.0 `ExecuteUpdate` and `ExecuteDelet ### Support for DbDataSource -TO BE COMPLETED +Npgsql 7.0 introduced , a major improvement to how database connections and configuration are managed in System.Data. enabled rich new configuration APIs, which are also available when using the Npgsql EF provider: + +```csharp +// Create a data source with the configuration you want: +var dataSourceBuilder = new NpgsqlDataSourceBuilder(builder.Configuration.GetConnectionString("MyContext")); +dataSourceBuilder + .UseLoggerFactory(loggerFactory) // Configure ADO.NET logging + .UsePeriodicPasswordProvider(); // Automatically rotate the password periodically +await using var dataSource = dataSourceBuilder.Build(); + +// Pass your data source to the EF provider: +builder.Services.AddDbContext(options => options.UseNpgsql(dataSource); +``` + +Note that the data source configuration works at the Npgsql ADO.NET layer, and is distinct from EF-level configuration. More improvements are planned in 8.0, to make data source usage more streamlined, especially around type mapping plugins, enums, etc. ### Extensive support for aggregate function translation EF Core 7.0 added support for translating provider-specific aggregate functions, and EFCore.PG builds on top of that to translate most major aggregate functions that PostgreSQL supports. This unlocks support for: -* string_agg: pack a column's values into a single string, with or without a delimiter. -* array_agg: pack a column's values into a PostgreSQL array. This can help with efficient fetching of dependent values, avoiding the so-called "cartesian explosion" problem. -* Statistical functions: standard deviation, variance and many others. -* Spatial functions: ST_Union, ST_Collect, ST_Extent and ST_ConvexHull. -* JSON functions: load values from the database as JSON documents with json_agg/jsonb_agg and json_object_agg/jsonb_object_agg. +* **string_agg**: pack a column's values into a single string, with or without a delimiter. +* **array_agg**: pack a column's values into a PostgreSQL array. This can help with efficient fetching of dependent values, avoiding the so-called "cartesian explosion" problem. +* **Statistical functions**: standard deviation, variance and many others. +* **Spatial functions**: ST_Union, ST_Collect, ST_Extent and ST_ConvexHull. +* **JSON functions**: load values from the database as JSON documents with json_agg/jsonb_agg and json_object_agg/jsonb_object_agg. For the PostgreSQL documentation on aggregate functions, see [this page](https://www.postgresql.org/docs/current/functions-aggregate.html). The exact translations supported by the provider are documented in the [translations page](../mapping/translations.md#aggregate-functions). ### Row value expressions -TO BE COMPLETED +The provider now supports translations which make use of *row value expressions*, which are conceptually similar to tuples. Row values are particularly useful for implementing *keyset pagination*, which is much more efficient than the common, offset-base pagination. To learn more about pagination techniques, see [this documentation page](https://learn.microsoft.com/ef/core/querying/pagination). + +Here's an example comparing two row values as an implementation of keyset pagination: + +```csharp +var nextPage = context.Posts + .OrderBy(b => b.Date) + .ThenBy(b => b.PostId) + .Where(b => EF.Functions.GreaterThan( + ValueTuple.Create(b.Date, b.PostId), + ValueTuple.Create(lastDate, lastId))) + .Take(10) + .ToList(); +``` + +This generates the following SQL: + +```sql +SELECT p."PostId", p."Date" +FROM "Posts" AS p +WHERE (p."Date", p."PostId") > (@__lastDate_1, @__lastId_2) +ORDER BY p."Date", p."PostId" +LIMIT @__p_3 +``` + +To the list of row value translations, see the [translations page](../mapping/translations.html#row-value-comparisons). ### Other new features @@ -33,6 +72,10 @@ TO BE COMPLETED ## Breaking changes +### Obsoleted UseXminAsConcurrencyToken + +Starting with version 7.0, concurrency token properties can be configured via the standard EF means, rather than the PostgreSQL-specific `UseXminAsConcurrencyToken`; simply configure any `uint` property with the `IsRowVersion()` Fluent API or the `[Timestamp]` Data Annotation. [See the documentation for more details](../modeling/concurrency.md). + ### Obsoleted default column collations Versions 6.0 and below had a mechanism that allowed defining a "default column collation", which is applied individually to every text column by default; this differed from the database collation, which is applied once to the database at creation time. This mechanism was introduced because in PostgreSQL, the database collation is quite limited, and for example does not allow specifying non-deterministic collations (e.g. case-insensitive ones). @@ -56,7 +99,3 @@ protected override void ConfigureConventions(ModelConfigurationBuilder configura configurationBuilder.Properties().UseCollation(""); } ``` - -### Obsoleted UseXminAsConcurrencyToken - -Starting with version 7.0, concurrency token properties can be configured via the standard EF means, rather than the PostgreSQL-specific `UseXminAsConcurrencyToken`; simply configure any `uint` property with the `IsRowVersion()` Fluent API or the `[Timestamp]` Data Annotation. [See the documentation for more details](../modeling/concurrency.md). From 6f7d0c94b8abbffab38d9214e493a0f13f4528ae Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Thu, 10 Nov 2022 18:10:54 +0200 Subject: [PATCH 124/207] Add toc link to EFCore.PG 7.0 release notes --- docs/toc.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/toc.yml b/docs/toc.yml index f6b9c020b6..81658da990 100644 --- a/docs/toc.yml +++ b/docs/toc.yml @@ -2,6 +2,8 @@ href: index.md - name: Release notes items: + - name: "7.0" + href: release-notes/7.0.md - name: "6.0" href: release-notes/6.0.md - name: "5.0" From b9b03eb66ec6f34f2b7d286a2bd2a7b893c731c0 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Thu, 10 Nov 2022 18:16:01 +0200 Subject: [PATCH 125/207] Move EFCore.PG 5.0 release notes to out of support --- docs/toc.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/toc.yml b/docs/toc.yml index 81658da990..5afb0b4659 100644 --- a/docs/toc.yml +++ b/docs/toc.yml @@ -6,12 +6,12 @@ href: release-notes/7.0.md - name: "6.0" href: release-notes/6.0.md - - name: "5.0" - href: release-notes/5.0.md - name: "3.1" href: release-notes/3.1.md - name: Out of support items: + - name: "5.0" + href: release-notes/5.0.md - name: "2.2" href: release-notes/2.2.md - name: "2.1" From 6bc26b4912e7d9a35149d8aa1fc005392fab92b9 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Mon, 14 Nov 2022 11:10:43 +0200 Subject: [PATCH 126/207] Fix some broken links --- docs/mapping/array.md | 2 +- docs/mapping/full-text-search.md | 2 +- docs/mapping/translations.md | 4 ++-- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/mapping/array.md b/docs/mapping/array.md index db9945f8c2..3f64ef136d 100644 --- a/docs/mapping/array.md +++ b/docs/mapping/array.md @@ -45,4 +45,4 @@ array.Any(s => EF.Functions.Like(string, s)) | [string LIKE ANY (array)](https: array.Any(s => EF.Functions.ILike(string, s)) | [string ILIKE ANY (array)](https://www.postgresql.org/docs/current/functions-comparisons.html#id-1.5.8.30.16) | array.All(s => EF.Functions.Like(string, s)) | [string LIKE ALL (array)](https://www.postgresql.org/docs/current/functions-comparisons.html#id-1.5.8.30.16) | array.All(s => EF.Functions.ILike(string, s)) | [string ILIKE ALL (array)](https://www.postgresql.org/docs/current/functions-comparisons.html#id-1.5.8.30.16) | -EF.Functions.ArrayAgg(values) | [array_agg(values)](https://www.postgresql.org/docs/current/functions-aggregate.html#FUNCTIONS-AGGREGATE-TABLE) | Added in 7.0, See [Aggregate functions](#aggregate-functions). +EF.Functions.ArrayAgg(values) | [array_agg(values)](https://www.postgresql.org/docs/current/functions-aggregate.html#FUNCTIONS-AGGREGATE-TABLE) | Added in 7.0, See [Aggregate functions](translations.md#aggregate-functions). diff --git a/docs/mapping/full-text-search.md b/docs/mapping/full-text-search.md index a1c10bccbf..f4b23cb4cd 100644 --- a/docs/mapping/full-text-search.md +++ b/docs/mapping/full-text-search.md @@ -34,7 +34,7 @@ public class Product } ``` -Setting up the column to be auto-updated depends on your PostgreSQL version. On PostgreSQL 12 and above, the column can be a simple [generated column](../modeling/generated-properties.md#computed-columns-on-add-or-update), and version 5.0.0 contains sugar for setting that up. In previous versions, you must manually set up database triggers that update the column instead. +Setting up the column to be auto-updated depends on your PostgreSQL version. On PostgreSQL 12 and above, the column can be a simple [generated column](../modeling/generated-properties.md#computed-columns), and version 5.0.0 contains sugar for setting that up. In previous versions, you must manually set up database triggers that update the column instead. #### [PostgreSQL 12+](#tab/pg12) diff --git a/docs/mapping/translations.md b/docs/mapping/translations.md index fbb9c86fbc..415e9e864f 100644 --- a/docs/mapping/translations.md +++ b/docs/mapping/translations.md @@ -151,7 +151,7 @@ Math.Tan(a) | tan(a) | Math.Truncate(d) | trunc(d) | EF.Functions.Random() | random() | Added in 6.0 -See also [Aggregate statistics functions](#aggregate-statistics-functions). +See also [Aggregate statistics functions](#aggregate-functions). ## Row value comparisons @@ -210,7 +210,7 @@ EF.Functions.Set7BitMac8(macaddr8) | [macaddr8_set7bit(macaddr8)]( The below translations provide functionality for determining the similarity of alphanumeric text based on trigram matching, using the [`pg_trgm`](https://www.postgresql.org/docs/current/pgtrgm.html) extension which is bundled with standard PostgreSQL distributions. All the below parameters are strings. > [!NOTE] -> Prior to version 6.0, to use these translations, your project must depend on the [Npgsql.EntityFrameworkCore.PostgreSQL.Trigrams](https://www.nuget.org/packages/Npgsql.EntityFrameworkCore.PostgreSQL.Trigrams/) package, and call in your `OnModelConfiguring`. +> Prior to version 6.0, to use these translations, your project must depend on the [Npgsql.EntityFrameworkCore.PostgreSQL.Trigrams](https://www.nuget.org/packages/Npgsql.EntityFrameworkCore.PostgreSQL.Trigrams/) package, and call `UseTrigrams()` in your `OnModelConfiguring`. .NET | SQL ----------------------------------------------------------------- | -------------------- From e5c79ba8ecd7bc4b50b43139ad1f87044ec28e70 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Mon, 14 Nov 2022 11:25:13 +0200 Subject: [PATCH 127/207] More link cleanup --- docs/release-notes/5.0.md | 2 +- docs/release-notes/7.0.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/release-notes/5.0.md b/docs/release-notes/5.0.md index 5fdac3a55b..779c6a2a17 100644 --- a/docs/release-notes/5.0.md +++ b/docs/release-notes/5.0.md @@ -7,7 +7,7 @@ Version 5.0 of the Npgsql Entity Framework Core provider has been released and i Aside from general EF Core features new in 5.0, here is a non-exhaustive list of features added in the Npgsql EF Core provider: * Full support for PostgreSQL collations. [See the docs](http://www.npgsql.org/efcore/misc/collations-and-case-sensitivity.html?tabs=data-annotations) for more info. -* It is now much easier to create indexes for full-text search ([#1097](https://github.com/npgsql/efcore.pg/issues/1097), [#1253](https://github.com/npgsql/efcore.pg/issues/1253)). [See the docs](www.npgsql.org/efcore/mapping/full-text-search.html) for more info. +* It is now much easier to create indexes for full-text search ([#1097](https://github.com/npgsql/efcore.pg/issues/1097), [#1253](https://github.com/npgsql/efcore.pg/issues/1253)). [See the docs](../mapping/full-text-search.md) for more info. * Sequences are now automatically updated after seeding data to avoid duplicate values ([#367](https://github.com/npgsql/efcore.pg/issues/367)). * [The `[JsonPropertyName]` attribute](https://docs.microsoft.com/dotnet/api/system.text.json.serialization.jsonpropertynameattribute) is now respected when mapping to JSON ([#1419](https://github.com/npgsql/efcore.pg/issues/1419)). * Improved support for PostgreSQL arrays: diff --git a/docs/release-notes/7.0.md b/docs/release-notes/7.0.md index 0360d10618..035ccad22a 100644 --- a/docs/release-notes/7.0.md +++ b/docs/release-notes/7.0.md @@ -63,7 +63,7 @@ ORDER BY p."Date", p."PostId" LIMIT @__p_3 ``` -To the list of row value translations, see the [translations page](../mapping/translations.html#row-value-comparisons). +To the list of row value translations, see the [translations page](../mapping/translations.md#row-value-comparisons). ### Other new features From 6562da980a31649b0e698fea8fd4843390c81a98 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Wed, 16 Nov 2022 14:05:11 +0100 Subject: [PATCH 128/207] Remove "new and experimental" on the retrying strategy docs --- docs/misc/other.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/misc/other.md b/docs/misc/other.md index eb43450c0d..23ea4e7ef9 100644 --- a/docs/misc/other.md +++ b/docs/misc/other.md @@ -21,7 +21,7 @@ protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) options => options.EnableRetryOnFailure()); ``` -This strategy relies on the `IsTransient` property of `NpgsqlException`. Both this property and the retrying strategy are new and should be considered somewhat experimental - please report any issues. +This strategy relies on the `IsTransient` property of `NpgsqlException`. ## Certificate authentication From 024590bd71421d48c9844c0a0a66a980f8f94aac Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Fri, 18 Nov 2022 11:57:57 +0100 Subject: [PATCH 129/207] Show GUID client-side gen for non-key properties --- docs/modeling/generated-properties.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/docs/modeling/generated-properties.md b/docs/modeling/generated-properties.md index 4663393f30..283a70ad0d 100644 --- a/docs/modeling/generated-properties.md +++ b/docs/modeling/generated-properties.md @@ -104,6 +104,18 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) By default, for GUID key properties, a random GUID is generated client-side by the EF provider and sent to the database. +To generate GUID's client-side for non-key properties, configure them as follows: + +```c# +protected override void OnModelCreating(ModelBuilder modelBuilder) +{ + modelBuilder + .Entity() + .Property(b => b.SomeGuidProperty) + .HasValueGenerator(); +} +``` + If you prefer to generate values in the database instead, you can do so by specifying `HasDefaultValueSql` on your property, and call the function to generate the value in the SQL expression. Which function to use depends on your PostgreSQL version: ### [PG 13+](#tab/13) From 9cea7b0f23f28a942f0ffbb6e7f0816106b869de Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Thu, 8 Dec 2022 17:00:46 +0100 Subject: [PATCH 130/207] Add 7.0 breaking change note for logging --- docs/release-notes/7.0.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/release-notes/7.0.md b/docs/release-notes/7.0.md index 035ccad22a..bd7e691e3b 100644 --- a/docs/release-notes/7.0.md +++ b/docs/release-notes/7.0.md @@ -72,6 +72,8 @@ To the list of row value translations, see the [translations page](../mapping/tr ## Breaking changes +Note: version 7.0 of the lower-level Npgsql ADO.NET driver, which is used by the EF provider, also has some breaking changes. It's recommended to read the [release notes](../../Npgsql/release-notes/7.0.md) for that as well. + ### Obsoleted UseXminAsConcurrencyToken Starting with version 7.0, concurrency token properties can be configured via the standard EF means, rather than the PostgreSQL-specific `UseXminAsConcurrencyToken`; simply configure any `uint` property with the `IsRowVersion()` Fluent API or the `[Timestamp]` Data Annotation. [See the documentation for more details](../modeling/concurrency.md). From 546d9e38706262e0ef9f8e92b009ef40503074d5 Mon Sep 17 00:00:00 2001 From: Brar Piening Date: Wed, 21 Dec 2022 11:50:05 +0100 Subject: [PATCH 131/207] Fix fixable warnings (#272) --- docs/mapping/full-text-search.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/mapping/full-text-search.md b/docs/mapping/full-text-search.md index f4b23cb4cd..4c4ad25a82 100644 --- a/docs/mapping/full-text-search.md +++ b/docs/mapping/full-text-search.md @@ -56,7 +56,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) } ``` -#### [Older Versions](#tab/older) +#### [Older Versions](#tab/pg-lt-12) First, modify the `OnModelCreating()` of your context class to add an index as follows: @@ -119,7 +119,7 @@ modelBuilder.Entity() .IsTsVectorExpressionIndex("english"); ``` -#### [Older Versions](#tab/older) +#### [Older Versions](#tab/lt-v5) Create a migration which will contain the index creation SQL (`dotnet ef migrations add ...`). At this point, open the generated migration with your editor and add the following: From 642c2ad0e34167d943d4cf887b731daadba01bb2 Mon Sep 17 00:00:00 2001 From: Nikita Kazmin Date: Thu, 29 Dec 2022 17:58:42 +0300 Subject: [PATCH 132/207] Fix build badge (#275) --- docs/index.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/index.md b/docs/index.md index fb43b708c3..cb68bc603c 100644 --- a/docs/index.md +++ b/docs/index.md @@ -3,7 +3,7 @@ [![stable](https://img.shields.io/nuget/v/Npgsql.EntityFrameworkCore.PostgreSQL.svg?label=stable)](https://www.nuget.org/packages/Npgsql.EntityFrameworkCore.PostgreSQL/) [![unstable](https://img.shields.io/myget/npgsql-unstable/vpre/Npgsql.EntityFrameworkCore.PostgreSQL.svg?label=unstable)](https://www.myget.org/feed/npgsql-unstable/package/nuget/Npgsql.EntityFrameworkCore.PostgreSQL) [![next patch](https://img.shields.io/myget/npgsql/v/Npgsql.EntityFrameworkCore.PostgreSQL.svg?label=next%20patch)](https://www.myget.org/feed/npgsql/package/nuget/Npgsql.EntityFrameworkCore.PostgreSQL) -[![build](https://img.shields.io/github/workflow/status/npgsql/efcore.pg/Build)](https://github.com/npgsql/efcore.pg/actions) +[![build](https://img.shields.io/github/actions/workflow/status/npgsql/efcore.pg/workflows/build.yml?branch=main)](https://github.com/npgsql/efcore.pg/actions) [![gitter](https://img.shields.io/badge/gitter-join%20chat-brightgreen.svg)](https://gitter.im/npgsql/npgsql) 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](https://docs.microsoft.com/ef/core/index) apply here as well. If you're just getting started with EF Core, those docs are the best place to start. From 1d213657150dc2aba99a6e26b0f0f6a1f4c12212 Mon Sep 17 00:00:00 2001 From: Nikita Kazmin Date: Thu, 29 Dec 2022 18:20:19 +0300 Subject: [PATCH 133/207] Second attempt to fix badge (#276) --- docs/index.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/index.md b/docs/index.md index cb68bc603c..7e4b19b89d 100644 --- a/docs/index.md +++ b/docs/index.md @@ -3,7 +3,7 @@ [![stable](https://img.shields.io/nuget/v/Npgsql.EntityFrameworkCore.PostgreSQL.svg?label=stable)](https://www.nuget.org/packages/Npgsql.EntityFrameworkCore.PostgreSQL/) [![unstable](https://img.shields.io/myget/npgsql-unstable/vpre/Npgsql.EntityFrameworkCore.PostgreSQL.svg?label=unstable)](https://www.myget.org/feed/npgsql-unstable/package/nuget/Npgsql.EntityFrameworkCore.PostgreSQL) [![next patch](https://img.shields.io/myget/npgsql/v/Npgsql.EntityFrameworkCore.PostgreSQL.svg?label=next%20patch)](https://www.myget.org/feed/npgsql/package/nuget/Npgsql.EntityFrameworkCore.PostgreSQL) -[![build](https://img.shields.io/github/actions/workflow/status/npgsql/efcore.pg/workflows/build.yml?branch=main)](https://github.com/npgsql/efcore.pg/actions) +[![build](https://img.shields.io/github/actions/workflow/status/npgsql/efcore.pg/build.yml?branch=main)](https://github.com/npgsql/efcore.pg/actions) [![gitter](https://img.shields.io/badge/gitter-join%20chat-brightgreen.svg)](https://gitter.im/npgsql/npgsql) 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](https://docs.microsoft.com/ef/core/index) apply here as well. If you're just getting started with EF Core, those docs are the best place to start. From 4d9cd10ebae031d9fd8187661891cd1459b91e5a Mon Sep 17 00:00:00 2001 From: Nikita Kazmin Date: Mon, 2 Jan 2023 00:31:01 +0300 Subject: [PATCH 134/207] Fix badge links (#277) --- docs/index.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/index.md b/docs/index.md index 7e4b19b89d..61d481fc1e 100644 --- a/docs/index.md +++ b/docs/index.md @@ -1,8 +1,8 @@ # Npgsql Entity Framework Core Provider [![stable](https://img.shields.io/nuget/v/Npgsql.EntityFrameworkCore.PostgreSQL.svg?label=stable)](https://www.nuget.org/packages/Npgsql.EntityFrameworkCore.PostgreSQL/) -[![unstable](https://img.shields.io/myget/npgsql-unstable/vpre/Npgsql.EntityFrameworkCore.PostgreSQL.svg?label=unstable)](https://www.myget.org/feed/npgsql-unstable/package/nuget/Npgsql.EntityFrameworkCore.PostgreSQL) [![next patch](https://img.shields.io/myget/npgsql/v/Npgsql.EntityFrameworkCore.PostgreSQL.svg?label=next%20patch)](https://www.myget.org/feed/npgsql/package/nuget/Npgsql.EntityFrameworkCore.PostgreSQL) +[![vnext](https://img.shields.io/myget/npgsql-vnext/vpre/Npgsql.EntityFrameworkCore.PostgreSQL.svg?label=vnext)](https://www.myget.org/feed/npgsql-vnext/package/nuget/Npgsql.EntityFrameworkCore.PostgreSQL) [![build](https://img.shields.io/github/actions/workflow/status/npgsql/efcore.pg/build.yml?branch=main)](https://github.com/npgsql/efcore.pg/actions) [![gitter](https://img.shields.io/badge/gitter-join%20chat-brightgreen.svg)](https://gitter.im/npgsql/npgsql) From bfb3acc7190a12dee5fa4b573d29738ee0f26e28 Mon Sep 17 00:00:00 2001 From: Peter Gummer Date: Tue, 10 Jan 2023 08:33:30 +1100 Subject: [PATCH 135/207] .NET array indexing starts at zero It's misleading to say that .NET array[1] maps to SQL array[1]. --- docs/mapping/array.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/mapping/array.md b/docs/mapping/array.md index 3f64ef136d..694657e07a 100644 --- a/docs/mapping/array.md +++ b/docs/mapping/array.md @@ -27,7 +27,7 @@ The provider can also translate CLR array operations to the corresponding SQL op .NET | SQL | Notes --------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- | ---- -array[1] | [array[1]](https://www.postgresql.org/docs/current/static/arrays.html#ARRAYS-ACCESSING) | +array[0] | [array[1]](https://www.postgresql.org/docs/current/static/arrays.html#ARRAYS-ACCESSING) | array.Length / list.Count | [cardinality(array)](https://www.postgresql.org/docs/current/static/functions-array.html#ARRAY-FUNCTIONS-TABLE) | array1 == array2 | [array1 = array2](https://www.postgresql.org/docs/current/static/arrays.html) | array1.SequenceEqual(array2) | [array1 = array2](https://www.postgresql.org/docs/current/static/arrays.html) | From b6cc8709ee746ead7174707122999c4ef54f4ed4 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Mon, 30 Jan 2023 11:16:45 +0100 Subject: [PATCH 136/207] Fix cross-link --- docs/mapping/range.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/mapping/range.md b/docs/mapping/range.md index 93cdbab8f4..390820f5e7 100644 --- a/docs/mapping/range.md +++ b/docs/mapping/range.md @@ -99,4 +99,4 @@ range1.Merge(range2) | [range_merge(range1, range2)](https://ww multirange.Merge() | [range_merge(multirange)](https://www.postgresql.org/docs/current/functions-range.html#MULTIRANGE-FUNCTIONS-TABLE) ranges.RangeAgg() | [range_agg(ranges)](https://www.postgresql.org/docs/current/functions-aggregate.html) ranges.RangeIntersectAgg() | [range_intersect_agg(ranges)](https://www.postgresql.org/docs/current/functions-aggregate.html) -multiranges.RangeIntersectAgg() | [range_intersect_agg(multiranges)](https://www.postgresql.org/docs/current/functions-aggregate.html) | Added in 7.0, See [Aggregate functions](#aggregate-functions). +multiranges.RangeIntersectAgg() | [range_intersect_agg(multiranges)](https://www.postgresql.org/docs/current/functions-aggregate.html) | Added in 7.0, See [Aggregate functions](translations.md#aggregate-functions). From 577dafd8bb68c0971b8866a62d0e72e2c84d931c Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Mon, 22 May 2023 09:54:22 +0200 Subject: [PATCH 137/207] Document new 8.0 array translations --- docs/mapping/array.md | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/docs/mapping/array.md b/docs/mapping/array.md index 694657e07a..700c5c3dc7 100644 --- a/docs/mapping/array.md +++ b/docs/mapping/array.md @@ -27,18 +27,22 @@ The provider can also translate CLR array operations to the corresponding SQL op .NET | SQL | Notes --------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- | ---- -array[0] | [array[1]](https://www.postgresql.org/docs/current/static/arrays.html#ARRAYS-ACCESSING) | +array[0] | [array\[1\]](https://www.postgresql.org/docs/current/arrays.html#ARRAYS-ACCESSING) | array.Length / list.Count | [cardinality(array)](https://www.postgresql.org/docs/current/static/functions-array.html#ARRAY-FUNCTIONS-TABLE) | +array.Skip(2) | [array\[3,\]](https://www.postgresql.org/docs/current/arrays.html#ARRAYS-ACCESSING) | Added in 8.0 +array.Take(2) | [array\[,2\]](https://www.postgresql.org/docs/current/arrays.html#ARRAYS-ACCESSING) | Added in 8.0 +array.Skip(1).Take(2) | [array\[2,3\]](https://www.postgresql.org/docs/current/arrays.html#ARRAYS-ACCESSING) | Added in 8.0 array1 == array2 | [array1 = array2](https://www.postgresql.org/docs/current/static/arrays.html) | array1.SequenceEqual(array2) | [array1 = array2](https://www.postgresql.org/docs/current/static/arrays.html) | -arrayNonColumn.Contains(element)) | [element = ANY(arrayNonColumn)](https://www.postgresql.org/docs/current/static/functions-comparisons.html#AEN21104) | Can use regular index +arrayNonColumn.Contains(element) | [element = ANY(arrayNonColumn)](https://www.postgresql.org/docs/current/static/functions-comparisons.html#AEN21104) | Can use regular index arrayColumn.Contains(element) | [arrayColumn @> ARRAY\[element\]](https://www.postgresql.org/docs/current/functions-array.html#ARRAY-OPERATORS-TABLE) | Can use GIN index array.Append(element) | [array_append(array, element)](https://www.postgresql.org/docs/current/functions-array.html#ARRAY-FUNCTIONS-TABLE) | Added in 6.0 -array1.Concat(array2) | [array_cat(array1, array2)](https://www.postgresql.org/docs/current/functions-array.html#ARRAY-FUNCTIONS-TABLE) | Added in 6.0 +array1.Concat(array2) | [array1 \|\| array2](https://www.postgresql.org/docs/current/functions-array.html#ARRAY-FUNCTIONS-TABLE) | Added in 6.0 array.IndexOf(element) | [array_position(array, element) - 1](https://www.postgresql.org/docs/current/functions-array.html#ARRAY-FUNCTIONS-TABLE) | Added in 6.0 array.IndexOf(element, startIndex) | [array_position(array, element, startIndex + 1) - 1](https://www.postgresql.org/docs/current/functions-array.html#ARRAY-FUNCTIONS-TABLE) | Added in 6.0 String.Join(separator, array) | [array_to_string(array, separator, '')](https://www.postgresql.org/docs/current/functions-array.html#ARRAY-FUNCTIONS-TABLE) | Added in 6.0 array.Any() | [cardinality(array) > 0](https://www.postgresql.org/docs/current/static/functions-array.html#ARRAY-FUNCTIONS-TABLE) | +array1.Intersect(array2).Any() | [array1 && array2](https://www.postgresql.org/docs/current/functions-array.html#ARRAY-OPERATORS-TABLE) | Added in 8.0 array1.Any(i => array2.Contains(i)) | [array1 && array2](https://www.postgresql.org/docs/current/functions-array.html#ARRAY-OPERATORS-TABLE) | array1.All(i => array2.Contains(i)) | [array1 <@ array2](https://www.postgresql.org/docs/current/functions-array.html#ARRAY-OPERATORS-TABLE) | array.Any(s => EF.Functions.Like(string, s)) | [string LIKE ANY (array)](https://www.postgresql.org/docs/current/functions-comparisons.html#id-1.5.8.30.16) | From 1686239a2b40131bd25d21a58626a37b64ed4cca Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Mon, 22 May 2023 11:04:34 +0200 Subject: [PATCH 138/207] Make markdownlint happy --- docs/mapping/full-text-search.md | 8 ++++---- docs/mapping/json.md | 12 ++++++------ 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/docs/mapping/full-text-search.md b/docs/mapping/full-text-search.md index 4c4ad25a82..d740b57210 100644 --- a/docs/mapping/full-text-search.md +++ b/docs/mapping/full-text-search.md @@ -160,7 +160,7 @@ Almost all PostgreSQL full text search functions can be called through LINQ quer ----------------------------------------------------------------------------|----- EF.Functions.ToTsVector(string) | [to_tsvector(string)](https://www.postgresql.org/docs/current/static/textsearch-controls.html#TEXTSEARCH-PARSING-DOCUMENTS) EF.Functions.ToTsVector("english", string) | [to_tsvector('english'::regconfig, string)](https://www.postgresql.org/docs/current/static/textsearch-controls.html#TEXTSEARCH-PARSING-DOCUMENTS) -EF.Functions.ToTsQuery(string)) | [to_tsquery(string)](https://www.postgresql.org/docs/current/static/textsearch-controls.html#TEXTSEARCH-PARSING-QUERIES) +EF.Functions.ToTsQuery(string) | [to_tsquery(string)](https://www.postgresql.org/docs/current/static/textsearch-controls.html#TEXTSEARCH-PARSING-QUERIES) EF.Functions.ToTsQuery("english", string ) | [to_tsquery('english'::regconfig, string)](https://www.postgresql.org/docs/current/static/textsearch-controls.html#TEXTSEARCH-PARSING-QUERIES) EF.Functions.PlainToTsQuery(string) | [plainto_tsquery(string)](https://www.postgresql.org/docs/current/static/textsearch-controls.html#TEXTSEARCH-PARSING-QUERIES) EF.Functions.PlainToTsQuery("english", string) | [plainto_tsquery('english'::regconfig, string)](https://www.postgresql.org/docs/current/static/textsearch-controls.html#TEXTSEARCH-PARSING-QUERIES) @@ -168,7 +168,7 @@ EF.Functions.PhraseToTsQuery(string) | [p EF.Functions.PhraseToTsQuery("english", string) | [phraseto_tsquery('english'::regconfig, string)](https://www.postgresql.org/docs/current/static/textsearch-controls.html#TEXTSEARCH-PARSING-QUERIES) EF.Functions.WebSearchToTsQuery(string) | [websearch_to_tsquery(string)](https://www.postgresql.org/docs/current/static/textsearch-controls.html#TEXTSEARCH-PARSING-QUERIES) EF.Functions.WebSearchToTsQuery("english", string) | [websearch_to_tsquery('english'::regconfig, string)](https://www.postgresql.org/docs/current/static/textsearch-controls.html#TEXTSEARCH-PARSING-QUERIES) -EF.functions.ArrayToTsVector(new[] { "a", "b" }) | [array_to_tsvector(ARRAY['a', 'b'])](https://www.postgresql.org/docs/current/functions-textsearch.html#TEXTSEARCH-FUNCTIONS-TABLE) +EF.functions.ArrayToTsVector(new[] { "a", "b" }) | [array_to_tsvector(ARRAY\['a', 'b'\])](https://www.postgresql.org/docs/current/functions-textsearch.html#TEXTSEARCH-FUNCTIONS-TABLE) NpgsqlTsVector.Parse(string) | [CAST(string AS tsvector)](https://www.postgresql.org/docs/current/static/sql-expressions.html#SQL-SYNTAX-TYPE-CASTS) NpgsqlTsQuery.Parse(string) | [CAST(queryString AS tsquery)](https://www.postgresql.org/docs/current/static/sql-expressions.html#SQL-SYNTAX-TYPE-CASTS) tsvector.Matches(string) | [tsvector @@ plainto_tsquery(string)](https://www.postgresql.org/docs/current/static/textsearch-intro.html#TEXTSEARCH-MATCHING) @@ -187,8 +187,8 @@ tsquery1.ToPhrase(tsquery2) | [t tsquery1.ToPhrase(tsquery2, distance) | [tsquery_phrase(tsquery1, tsquery2, distance)](https://www.postgresql.org/docs/current/functions-textsearch.html#TEXTSEARCH-FUNCTIONS-TABLE) tsvector1.Concat(tsvector2) | [tsvector1 \|\| tsvector2](https://www.postgresql.org/docs/current/functions-textsearch.html#TEXTSEARCH-OPERATORS-TABLE) tsvector.Delete("x") | [ts_delete(tsvector, 'x')](https://www.postgresql.org/docs/current/functions-textsearch.html#TEXTSEARCH-FUNCTIONS-TABLE) -tsvector.Delete(new[] { "x", "y" }) | [ts_delete(tsvector, ARRAY['x', 'y'])](https://www.postgresql.org/docs/current/functions-textsearch.html#TEXTSEARCH-FUNCTIONS-TABLE) -tsvector.Filter(new[] { "x", "y" }) | [ts_filter(tsvector, ARRAY['x', 'y'])](https://www.postgresql.org/docs/current/functions-textsearch.html#TEXTSEARCH-FUNCTIONS-TABLE) +tsvector.Delete(new[] { "x", "y" }) | [ts_delete(tsvector, ARRAY\['x', 'y'\])](https://www.postgresql.org/docs/current/functions-textsearch.html#TEXTSEARCH-FUNCTIONS-TABLE) +tsvector.Filter(new[] { "x", "y" }) | [ts_filter(tsvector, ARRAY\['x', 'y'\])](https://www.postgresql.org/docs/current/functions-textsearch.html#TEXTSEARCH-FUNCTIONS-TABLE) tsvector.GetLength() | [length(tsvector)](https://www.postgresql.org/docs/current/functions-textsearch.html#TEXTSEARCH-FUNCTIONS-TABLE) tsvector.Rank(tsquery) | [ts_rank(tsvector, tsquery)](https://www.postgresql.org/docs/current/textsearch-controls.html#TEXTSEARCH-RANKING) tsvector.RankCoverDensity(tsquery) | [ts_rank_cd(tsvector, tsquery)](https://www.postgresql.org/docs/current/textsearch-controls.html#TEXTSEARCH-RANKING) diff --git a/docs/mapping/json.md b/docs/mapping/json.md index f065bd7ac4..a620eae300 100644 --- a/docs/mapping/json.md +++ b/docs/mapping/json.md @@ -204,13 +204,13 @@ The following expression types and functions are translated: .NET | SQL --------------------------------------------------------------------------------------- | ---- customer.Name | [customer->>'Name'](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-OP-TABLE) -customer.Orders[1].Price | [customer#>>'{Orders,0,Price}'[1]](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-OP-TABLE) +customer.Orders[1].Price | [customer#>>'{Orders,0,Price}'\[1\]](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-OP-TABLE) customer.Orders.Length (or Count) | [jsonb_array_length(customer->'Orders')](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-PROCESSING-TABLE) EF.Functions.JsonContains(customer, @"{""Name"": ""Joe"", ""Age"": 25}")1 | [customer @> '{"Name": "Joe", "Age": 25}'](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) EF.Functions.JsonContained(@"{""Name"": ""Joe"", ""Age"": 25}", e.Customer)1 | ['{"Name": "Joe", "Age": 25}' <@ customer](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) EF.Functions.JsonExists(e.Customer, "Age") | [customer ? 'Age'](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) -EF.Functions.JsonExistsAny(e.Customer, "Age", "Address") | [customer ?\| ARRAY['Age','Address']](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) -EF.Functions.JsonExistsAll(e.Customer, "Age", "Address") | [customer ?& ARRAY['Age','Address']](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) +EF.Functions.JsonExistsAny(e.Customer, "Age", "Address") | [customer ?\| ARRAY\['Age','Address'\]](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) +EF.Functions.JsonExistsAll(e.Customer, "Age", "Address") | [customer ?& ARRAY\['Age','Address'\]](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) EF.Functions.JsonTypeof(e.Customer.Age) | [jsonb_typeof(customer->'Age')](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-PROCESSING-TABLE) ### [JsonDocument Mapping](#tab/jsondocument) @@ -218,13 +218,13 @@ EF.Functions.JsonTypeof(e.Customer.Age) .NET | SQL ------------------------------------------------------------------------------------- | ---- customer.RootElement.GetProperty("Name").GetString() | [customer->>'Name' = 'Joe'](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-OP-TABLE) -customer.RootElement.GetProperty("Orders")[1].GetProperty("Price").GetInt32() | [customer#>>'{Orders,0,Price}'[1] = 8](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-OP-TABLE) +customer.RootElement.GetProperty("Orders")[1].GetProperty("Price").GetInt32() | [customer#>>'{Orders,0,Price}'\[1\] = 8](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-OP-TABLE) customer.RootElement.GetProperty("Orders").GetArrayLength() | [jsonb_array_length(customer->'Orders'](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-PROCESSING-TABLE) EF.Functions.JsonContains(customer, @"{""Name"": ""Joe"", ""Age"": 25}")1 | [customer @> '{"Name": "Joe", "Age": 25}'](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) EF.Functions.JsonContained(@"{""Name"": ""Joe"", ""Age"": 25}", customer)1 | ['{"Name": "Joe", "Age": 25}' <@ customer](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) EF.Functions.JsonExists(customer, "Age") | [customer ? 'Age'](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) -EF.Functions.JsonExistsAny(customer, "Age", "Address") | [customer ?\| ARRAY['Age','Address']](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) -EF.Functions.JsonExistsAll(customer, "Age", "Address") | [customer ?& ARRAY['Age','Address']](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) +EF.Functions.JsonExistsAny(customer, "Age", "Address") | [customer ?\| ARRAY\['Age','Address'\]](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) +EF.Functions.JsonExistsAll(customer, "Age", "Address") | [customer ?& ARRAY\['Age','Address'\]](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) EF.Functions.JsonTypeof(customer.GetProperty("Age")) == "number" | [jsonb_typeof(customer->'Age') = 'number'](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-PROCESSING-TABLE) *** From c32f2772be11feef70d6a9421bf2dfe723b66449 Mon Sep 17 00:00:00 2001 From: Samuel Meenzen Date: Mon, 12 Jun 2023 14:40:53 +0200 Subject: [PATCH 139/207] Fix typo in collations-and-case-sensitivity.md (#290) quote limited -> quite limited --- docs/misc/collations-and-case-sensitivity.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/misc/collations-and-case-sensitivity.md b/docs/misc/collations-and-case-sensitivity.md index 4286c5b653..b3154d7cf5 100644 --- a/docs/misc/collations-and-case-sensitivity.md +++ b/docs/misc/collations-and-case-sensitivity.md @@ -51,7 +51,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) } ``` -Unfortunately, the database collation is quote limited in PostgreSQL; it notably does not support non-deterministic collations (e.g. case-insensitive ones). To work around this limitation, you can use EF Core's [pre-convention model configuration](https://docs.microsoft.com/ef/core/modeling/bulk-configuration#pre-convention-configuration) feature: +Unfortunately, the database collation is quite limited in PostgreSQL; it notably does not support non-deterministic collations (e.g. case-insensitive ones). To work around this limitation, you can use EF Core's [pre-convention model configuration](https://docs.microsoft.com/ef/core/modeling/bulk-configuration#pre-convention-configuration) feature: ```c# protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder) From 1aa48f26f9376585b6715387553608a2603ec311 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Wed, 14 Jun 2023 14:44:17 +0200 Subject: [PATCH 140/207] Update EFCore.PG docs for NpgsqlDataSource usage (#292) --- docs/mapping/enum.md | 32 ++++++++++++++++++++------------ docs/mapping/nodatime.md | 38 +++++++++++++++++++++++++++++++------- docs/mapping/nts.md | 40 ++++++++++++++++++++++++++++++++-------- 3 files changed, 83 insertions(+), 27 deletions(-) diff --git a/docs/mapping/enum.md b/docs/mapping/enum.md index b177a49d40..6c8ad27ac0 100644 --- a/docs/mapping/enum.md +++ b/docs/mapping/enum.md @@ -8,22 +8,11 @@ However, the Npgsql provider also allows you to map your CLR enums to [database First, you must specify the PostgreSQL enum type on your model, just like you would with tables, sequences or other databases objects: -### [Version 2.2+](#tab/tabid-1) - ```c# protected override void OnModelCreating(ModelBuilder builder) => builder.HasPostgresEnum(); ``` -### [Version 2.1](#tab/tabid-2) - -```c# -protected override void OnModelCreating(ModelBuilder builder) - => builder.HasPostgresEnum("mood", new[] { "happy", "sad" }); -``` - ---- - This causes the EF Core provider to create your enum type, `mood`, with two labels: `happy` and `sad`. This will cause the appropriate migration to be created. If you are using `context.Database.Migrate()` to create your enums, you need to instruct Npgsql to reload all types after applying your migrations: @@ -40,13 +29,32 @@ using (var conn = (NpgsqlConnection)context.Database.GetDbConnection()) ## Mapping your enum -Even if your database enum is created, Npgsql has to know about it, and especially about your CLR enum type that should be mapped to it. This is done by adding the following code, *before* any EF Core operations take place. An appropriate place for this is in the static constructor on your DbContext class: +Even if your database enum is created, Npgsql has to know about it, and especially about your CLR enum type that should be mapped to it: + +### [NpgsqlDataSource](#tab/with-datasource) + +Since version 7.0, NpgsqlDataSource is the recommended way to use Npgsql. When using NpgsqlDataSource, map your enum when building your data source: + +```c# +// Call UseNodaTime() when building your data source: +var dataSourceBuilder = new NpgsqlDataSourceBuilder(/* connection string */); +dataSourceBuilder.MapEnum(); +var dataSource = dataSourceBuilder.Build(); + +builder.Services.AddDbContext(options => options.UseNpgsql(dataSource)); +``` + +### [Without NpgsqlDatasource](#tab/without-datasource) + +Since version 7.0, NpgsqlDataSource is the recommended way to use Npgsql. However, if you're not yet using NpgsqlDataSource, map enums by adding the following code, *before* any EF Core operations take place. An appropriate place for this is in the static constructor on your DbContext class: ```c# static MyDbContext() => NpgsqlConnection.GlobalTypeMapper.MapEnum(); ``` +*** + This code lets Npgsql know that your CLR enum type, `Mood`, should be mapped to a database enum called `mood`. Note that if your enum is in a custom schema (not `public`), you must specify that schema in the call to `MapEnum`. If you're curious as to inner workings, this code maps the enum with the ADO.NET provider - [see here for the full docs](http://www.npgsql.org/doc/types/enums_and_composites.html). When the Npgsql EF Core first initializes, it calls into the ADO.NET provider to get all mapped enums, and sets everything up internally at the EF Core layer as well. diff --git a/docs/mapping/nodatime.md b/docs/mapping/nodatime.md index 397f6334c9..bb627438e3 100644 --- a/docs/mapping/nodatime.md +++ b/docs/mapping/nodatime.md @@ -12,17 +12,41 @@ Beyond NodaTime's general advantages, some specific advantages NodaTime for Post ## Setup -To set up the NodaTime plugin, add the [Npgsql.EntityFrameworkCore.PostgreSQL.NodaTime nuget](https://www.nuget.org/packages/Npgsql.EntityFrameworkCore.PostgreSQL.NodaTime) to your project. Then, make the following modification to your `UseNpgsql()` line: +To set up the NodaTime plugin, add the [Npgsql.EntityFrameworkCore.PostgreSQL.NodaTime nuget](https://www.nuget.org/packages/Npgsql.EntityFrameworkCore.PostgreSQL.NodaTime) to your project. Then, configure NodaTime as follows: + +### [NpgsqlDataSource](#tab/with-datasource) + +Since version 7.0, NpgsqlDataSource is the recommended way to use Npgsql. When using NpsgqlDataSource, NodaTime currently has to be configured twice - once at the EF level, and once at the underlying ADO.NET level (there are plans to improve this): ```c# -protected override void OnConfiguring(DbContextOptionsBuilder builder) -{ - builder.UseNpgsql("Host=localhost;Database=test;Username=npgsql_tests;Password=npgsql_tests", - o => o.UseNodaTime()); -} +// Call UseNodaTime() when building your data source: +var dataSourceBuilder = new NpgsqlDataSourceBuilder(/* connection string */); +dataSourceBuilder.UseNodaTime(); +var dataSource = dataSourceBuilder.Build(); + +// Then, when configuring EF Core with UseNpgsql(), call UseNodaTime() there as well: +builder.Services.AddDbContext(options => + options.UseNpgsql(dataSource, o => o.UseNodaTime())); +``` + +### [Without NpgsqlDatasource](#tab/without-datasource) + +Since version 7.0, NpgsqlDataSource is the recommended way to use Npgsql. However, if you're not yet using NpgsqlDataSource, configure NodaTime as follows: + +```c# +// Configure NodaTime at the ADO.NET level. +// This code must be placed at the beginning of your application, before any other Npgsql API is called; an appropriate place for this is in the static constructor on your DbContext class: +static MyDbContext() + => NpgsqlConnection.GlobalTypeMapper.UseNodaTime(); + +// Then, when configuring EF Core with UseNpgsql(), call UseNodaTime(): +builder.Services.AddDbContext(options => + options.UseNpgsql(/* connection string */, o => o.UseNodaTime())); ``` -This will set up all the necessary mappings and operation translators. You can now use NodaTime types as regular properties in your entities, and even perform some operations: +*** + +The above sets up all the necessary mappings and operation translators. You can now use NodaTime types as regular properties in your entities, and even perform some operations: ```c# public class Post diff --git a/docs/mapping/nts.md b/docs/mapping/nts.md index 5f033d2f05..4a08c52c7b 100644 --- a/docs/mapping/nts.md +++ b/docs/mapping/nts.md @@ -5,21 +5,45 @@ PostgreSQL supports spatial data and operations via [the PostGIS extension](https://postgis.net/), which is a mature and feature-rich database spatial implementation. .NET doesn't provide a standard spatial library, but [NetTopologySuite](https://github.com/NetTopologySuite/NetTopologySuite) is a leading spatial library. The Npgsql EF Core provider has a plugin which allows you to map the NTS types to PostGIS columns, allowing seamless reading and writing. This is the recommended way to interact with spatial types in Npgsql. -Note that the EF Core NetTopologySuite plugin depends on [the Npgsql ADO.NET NetTopology plugin](http://www.npgsql.org/doc/types/nts.html), which provides NetTopologySuite support at the lower level. The EF Core plugin automatically sets up the ADO.NET plugin. +Note that the EF Core NetTopologySuite plugin depends on [the Npgsql ADO.NET NetTopology plugin](http://www.npgsql.org/doc/types/nts.html), which provides NetTopologySuite support at the lower level. ## Setup -To use the NetTopologySuite plugin, add the [Npgsql.EntityFrameworkCore.PostgreSQL.NetTopologySuite nuget](https://www.nuget.org/packages/Npgsql.EntityFrameworkCore.PostgreSQL.NetTopologySuite) to your project. Then, make the following modification to your `UseNpgsql()` line: +To use the NetTopologySuite plugin, add the [Npgsql.EntityFrameworkCore.PostgreSQL.NetTopologySuite nuget](https://www.nuget.org/packages/Npgsql.EntityFrameworkCore.PostgreSQL.NetTopologySuite) to your project. Then, configure NetTopologySuite as followed: + +### [NpgsqlDataSource](#tab/with-datasource) + +Since version 7.0, NpgsqlDataSource is the recommended way to use Npgsql. When using NpsgqlDataSource, NetTopologySuite currently has to be configured twice - once at the EF level, and once at the underlying ADO.NET level (there are plans to improve this): ```c# -protected override void OnConfiguring(DbContextOptionsBuilder builder) -{ - builder.UseNpgsql("Host=localhost;Database=test;Username=npgsql_tests;Password=npgsql_tests", - o => o.UseNetTopologySuite()); -} +// Call UseNetTopologySuite() when building your data source: +var dataSourceBuilder = new NpgsqlDataSourceBuilder(/* connection string */); +dataSourceBuilder.UseNetTopologySuite(); +var dataSource = dataSourceBuilder.Build(); + +// Then, when configuring EF Core with UseNpgsql(), call UseNetTopologySuite() there as well: +builder.Services.AddDbContext(options => + options.UseNpgsql(dataSource, o => o.UseNetTopologySuite())); +``` + +### [Without NpgsqlDatasource](#tab/without-datasource) + +Since version 7.0, NpgsqlDataSource is the recommended way to use Npgsql. However, if you're not yet using NpgsqlDataSource, configure NetTopologySuite as follows: + +```c# +// Configure NetTopologySuite at the ADO.NET level. +// This code must be placed at the beginning of your application, before any other Npgsql API is called; an appropriate place for this is in the static constructor on your DbContext class: +static MyDbContext() + => NpgsqlConnection.GlobalTypeMapper.UseNetTopologySuite(); + +// Then, when configuring EF Core with UseNpgsql(), call UseNetTopologySuite(): +builder.Services.AddDbContext(options => + options.UseNpgsql(/* connection string */, o => o.UseNetTopologySuite())); ``` -This sets up all the necessary mappings and operation translators. In addition, to make sure that the PostGIS extension is installed in your database, add the following to your DbContext: +*** + +The above sets up all the necessary EF mappings and operation translators. In addition, to make sure that the PostGIS extension is installed in your database, add the following to your DbContext: ```c# protected override void OnModelCreating(ModelBuilder builder) From 0e2cff5ef2606d3a379f5acaf32f1c7836135de1 Mon Sep 17 00:00:00 2001 From: Anton Sedyshev Date: Wed, 19 Jul 2023 20:25:12 +0300 Subject: [PATCH 141/207] Enums types reload after migration fix. (#295) --- docs/mapping/enum.md | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/docs/mapping/enum.md b/docs/mapping/enum.md index 6c8ad27ac0..c09a5a8754 100644 --- a/docs/mapping/enum.md +++ b/docs/mapping/enum.md @@ -18,12 +18,19 @@ This causes the EF Core provider to create your enum type, `mood`, with two labe If you are using `context.Database.Migrate()` to create your enums, you need to instruct Npgsql to reload all types after applying your migrations: ```c# -context.Database.Migrate(); +await context.Database.MigrateAsync(token); -using (var conn = (NpgsqlConnection)context.Database.GetDbConnection()) +if (context.Database.GetDbConnection() is NpgsqlConnection npgsqlConnection) { - conn.Open(); - conn.ReloadTypes(); + await npgsqlConnection.OpenAsync(token); + try + { + await npgsqlConnection.ReloadTypesAsync(); + } + finally + { + await npgsqlConnection.CloseAsync(); + } } ``` From 485544267504aba679d044f762818c6228fb3af4 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Thu, 2 Feb 2023 11:41:28 +0100 Subject: [PATCH 142/207] Document StringToArray See https://github.com/npgsql/efcore.pg/issues/2636 --- docs/mapping/translations.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/mapping/translations.md b/docs/mapping/translations.md index 415e9e864f..b77baf890d 100644 --- a/docs/mapping/translations.md +++ b/docs/mapping/translations.md @@ -45,6 +45,8 @@ Regex.IsMatch(stringValue, "^A+", regexOptions) | [stringValue ~ ' string.Join(", ", a, b) | [concat_ws(', ', a, b)](https://www.postgresql.org/docs/current/functions-string.html#FUNCTIONS-STRING-OTHER) | Added in 7.0 (previously array_to_string) string.Join(", ", array) | [array_to_string(array, ', ', '')](https://www.postgresql.org/docs/current/functions-array.html#ARRAY-FUNCTIONS-TABLE) string.Join(", ", agg_strings) | [string_agg(agg_strings, ', ')](https://www.postgresql.org/docs/current/functions-aggregate.html#FUNCTIONS-AGGREGATE-TABLE) | Added in 7.0, see [Aggregate functions](#aggregate-functions). +EF.Functions.StringToArray(s, "|") | [string_agg(s, '|')](https://www.postgresql.org/docs/current/functions-string.html#FUNCTION-STRING-TO-ARRAY) | Added in 8.0 +EF.Functions.StringToArray(s, "|", "FOO") | [string_agg(s, '|', 'FOO')](https://www.postgresql.org/docs/current/functions-string.html#FUNCTION-STRING-TO-ARRAY) | Added in 8.0 ## Date and time functions From 5ab3ad88a7be6f067e2b24970f2f26dea13a41b7 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Tue, 5 Sep 2023 14:02:26 +0300 Subject: [PATCH 143/207] Tiny markdown fixes in translation docs (#302) --- docs/mapping/translations.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/mapping/translations.md b/docs/mapping/translations.md index b77baf890d..b533ecb150 100644 --- a/docs/mapping/translations.md +++ b/docs/mapping/translations.md @@ -45,8 +45,8 @@ Regex.IsMatch(stringValue, "^A+", regexOptions) | [stringValue ~ ' string.Join(", ", a, b) | [concat_ws(', ', a, b)](https://www.postgresql.org/docs/current/functions-string.html#FUNCTIONS-STRING-OTHER) | Added in 7.0 (previously array_to_string) string.Join(", ", array) | [array_to_string(array, ', ', '')](https://www.postgresql.org/docs/current/functions-array.html#ARRAY-FUNCTIONS-TABLE) string.Join(", ", agg_strings) | [string_agg(agg_strings, ', ')](https://www.postgresql.org/docs/current/functions-aggregate.html#FUNCTIONS-AGGREGATE-TABLE) | Added in 7.0, see [Aggregate functions](#aggregate-functions). -EF.Functions.StringToArray(s, "|") | [string_agg(s, '|')](https://www.postgresql.org/docs/current/functions-string.html#FUNCTION-STRING-TO-ARRAY) | Added in 8.0 -EF.Functions.StringToArray(s, "|", "FOO") | [string_agg(s, '|', 'FOO')](https://www.postgresql.org/docs/current/functions-string.html#FUNCTION-STRING-TO-ARRAY) | Added in 8.0 +EF.Functions.StringToArray(s, "|") | [string_agg(s, '\|')](https://www.postgresql.org/docs/current/functions-string.html#FUNCTION-STRING-TO-ARRAY) | Added in 8.0 +EF.Functions.StringToArray(s, "|", "FOO") | [string_agg(s, '\|', 'FOO')](https://www.postgresql.org/docs/current/functions-string.html#FUNCTION-STRING-TO-ARRAY) | Added in 8.0 ## Date and time functions From 5d776b0e597fe87b6270d7706592ab93ce8bc467 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Thu, 7 Sep 2023 11:55:05 +0200 Subject: [PATCH 144/207] Fix incorrect Has/UseCollection Fixes #303 --- docs/misc/collations-and-case-sensitivity.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/misc/collations-and-case-sensitivity.md b/docs/misc/collations-and-case-sensitivity.md index b3154d7cf5..48ce06299a 100644 --- a/docs/misc/collations-and-case-sensitivity.md +++ b/docs/misc/collations-and-case-sensitivity.md @@ -47,7 +47,7 @@ PostgreSQL also allows you to specify collations at the database level, when it ```c# protected override void OnModelCreating(ModelBuilder modelBuilder) { - modelBuilder.HasCollation(""); + modelBuilder.UseCollation(""); } ``` From 6b3ed36995bf4a43182e4a04228cbde2f5d8543f Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Wed, 11 Oct 2023 15:00:56 +0200 Subject: [PATCH 145/207] Some release notes and breaking changes for 8.0 (#306) --- docs/release-notes/8.0.md | 52 +++++++++++++++++++++++++++++++++++++++ docs/toc.yml | 6 +++-- 2 files changed, 56 insertions(+), 2 deletions(-) create mode 100644 docs/release-notes/8.0.md diff --git a/docs/release-notes/8.0.md b/docs/release-notes/8.0.md new file mode 100644 index 0000000000..7418dbc542 --- /dev/null +++ b/docs/release-notes/8.0.md @@ -0,0 +1,52 @@ +# 8.0 Release Notes + +**The below release notes and breaking changes list aren't yet complete. Check back soon for more notes.** + +## New features + +New features will be documented later. + +## Breaking changes + +Note: version 8.0 of the lower-level Npgsql ADO.NET driver, which is used by the EF provider, also has some breaking changes. It's recommended to read the [release notes](../../Npgsql/release-notes/8.0.md) for that as well. + +### JSON POCO and other dynamic features now require an explicit opt-in + +Because of the NativeAOT and trimming work done for Npgsql 8.0 ([release notes](../../Npgsql/release-notes/8.0.md)), certain features now require an explicit opt-in, which you must add either on your or on : + +PostgreSQL type | Default .NET type +---------------------------------------- | -------------------------- +JSON POCO mapping, JsonNode and subtypes | +Unmapped enums, ranges, multiranges | +Read PostgreSQL records as .NET tuples | + +Existing code using the above features will start throwing exceptions after upgrading to version 8.0 of the EF Core provider; the exceptions provide explicit guidance on how to add the opt-ins. + +Note that EF Core itself is not yet compatible with NativeAOT, and Npgsql can only be used in NativeAOT applications without EF Core. + +### Obsoleted HasPostgresArrayConversion + +With EF 8.0 introducing first-class support for [primitive collections](https://devblogs.microsoft.com/dotnet/announcing-ef8-preview-4), the PostgreSQL driver aligned its PostgreSQL array support to use that. As a result, `HasPostgresArrayConversion` can no longer be used to configure value-converted arrays; instead, the new standard EF mechanism can be used. + +For example, the following Npgsql-specific code would configure value conversion for a property of type `MyType[]` to a PostgreSQL array of strings in EF Core 6 or 7: + +```c# +modelBuilder.Entity().Property(b => b.ValueConvertedArray) + .HasPostgresArrayConversion(x => x.ToString(), s => MyType.Parse(s)); +``` + +The same can now achieved with the following standard EF 8 code: + +```c# +modelBuilder.Entity().PrimitiveCollection(b => b.ValueConvertedArray) + .ElementType() + .HasConversion(typeof(MyConverter)); + +class MyConverter : ValueConverter +{ + public MyConverter() + : base(x => x.ToString(), s => MyType.Parse(s)) + { + } +} +``` diff --git a/docs/toc.yml b/docs/toc.yml index 5afb0b4659..46c8cccbed 100644 --- a/docs/toc.yml +++ b/docs/toc.yml @@ -2,16 +2,18 @@ href: index.md - name: Release notes items: + - name: "8.0" + href: release-notes/8.0.md - name: "7.0" href: release-notes/7.0.md - name: "6.0" href: release-notes/6.0.md - - name: "3.1" - href: release-notes/3.1.md - name: Out of support items: - name: "5.0" href: release-notes/5.0.md + - name: "3.1" + href: release-notes/3.1.md - name: "2.2" href: release-notes/2.2.md - name: "2.1" From cf1f68c62251bd7c9eb0acbdd56aae0267fa2fee Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Wed, 11 Oct 2023 16:27:44 +0200 Subject: [PATCH 146/207] Document networking mapping changes (#307) --- docs/mapping/translations.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/docs/mapping/translations.md b/docs/mapping/translations.md index b533ecb150..8234bc27d3 100644 --- a/docs/mapping/translations.md +++ b/docs/mapping/translations.md @@ -173,6 +173,9 @@ ValueTuple.Create(a, b).Equals(ValueTuple.Create(c, d)) ## Network functions +> [!NOTE] +> As of Npgsql 8.0, `IPAddress` and `NpgsqlCidr` are implicitly convertible to `NpgsqlInet`, and so can be used with the functions below which accept `inet`. + .NET | SQL ------------------------------------------------ | --- IPAddress.Parse(string) | [CAST(string AS inet)](https://www.postgresql.org/docs/current/datatype-net-types.html#DATATYPE-INET) @@ -193,6 +196,7 @@ EF.Functions.Add(inet, int) | [inet + int](https://www.post EF.Functions.Subtract(inet, int) | [inet - int](https://www.postgresql.org/docs/current/functions-net.html#CIDR-INET-OPERATORS-TABLE) EF.Functions.Subtract(inet1, inet2) | [inet1 - inet2](https://www.postgresql.org/docs/current/functions-net.html#CIDR-INET-OPERATORS-TABLE) EF.Functions.Abbreviate(inet) | [abbrev(inet)](https://www.postgresql.org/docs/current/functions-net.html#CIDR-INET-FUNCTIONS-TABLE) +EF.Functions.Abbreviate(cidr) | [abbrev(cidr)](https://www.postgresql.org/docs/current/functions-net.html#CIDR-INET-FUNCTIONS-TABLE) EF.Functions.Broadcast(inet) | [broadcast(inet)](https://www.postgresql.org/docs/current/functions-net.html#CIDR-INET-FUNCTIONS-TABLE) EF.Functions.Family(inet) | [family(inet)](https://www.postgresql.org/docs/current/functions-net.html#CIDR-INET-FUNCTIONS-TABLE) EF.Functions.Host(inet) | [host(inet)](https://www.postgresql.org/docs/current/functions-net.html#CIDR-INET-FUNCTIONS-TABLE) @@ -201,6 +205,7 @@ EF.Functions.MaskLength(inet) | [masklen(inet)](https://www.p EF.Functions.Netmask(inet) | [netmask(inet)](https://www.postgresql.org/docs/current/functions-net.html#CIDR-INET-FUNCTIONS-TABLE) EF.Functions.Network(inet) | [network(inet)](https://www.postgresql.org/docs/current/functions-net.html#CIDR-INET-FUNCTIONS-TABLE) EF.Functions.SetMaskLength(inet) | [set_masklen(inet)](https://www.postgresql.org/docs/current/functions-net.html#CIDR-INET-FUNCTIONS-TABLE) +EF.Functions.SetMaskLength(cidr) | [set_masklen(cidr)](https://www.postgresql.org/docs/current/functions-net.html#CIDR-INET-FUNCTIONS-TABLE) EF.Functions.Text(inet) | [text(inet)](https://www.postgresql.org/docs/current/functions-net.html#CIDR-INET-FUNCTIONS-TABLE) EF.Functions.SameFamily(inet1, inet2) | [inet_same_family(inet1, inet2)](https://www.postgresql.org/docs/current/functions-net.html#CIDR-INET-FUNCTIONS-TABLE) EF.Functions.Merge(inet1, inet2) | [inet_merge(inet1, inet2)](https://www.postgresql.org/docs/current/functions-net.html#CIDR-INET-FUNCTIONS-TABLE) From 6e286a4aff026f36fa15ae59487d40fed79c49cd Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Sat, 28 Oct 2023 10:19:47 +0200 Subject: [PATCH 147/207] Documentation on storage parameters (#312) Following https://github.com/npgsql/efcore.pg/pull/2914 --- docs/modeling/indexes.md | 13 +++++++++++++ .../{table-column-naming.md => tables.md} | 15 ++++++++++++++- docs/release-notes/8.0.md | 2 ++ docs/toc.yml | 8 ++++---- 4 files changed, 33 insertions(+), 5 deletions(-) rename docs/modeling/{table-column-naming.md => tables.md} (72%) diff --git a/docs/modeling/indexes.md b/docs/modeling/indexes.md index 5dbf90faa8..b3e02ecbd9 100644 --- a/docs/modeling/indexes.md +++ b/docs/modeling/indexes.md @@ -63,6 +63,19 @@ Note that each operator class is used for the corresponding index column, by ord CREATE INDEX "IX_blogs_Id_Name" ON blogs ("Id", "Name" text_pattern_ops); ``` +## Storage parameters + +PostgreSQL allows configuring indexes with *storage parameters*, which can tweak their behaviors in various ways; which storage parameters are available depends on the chosen index method. [See the PostgreSQL documentation](https://www.postgresql.org/docs/current/sql-createindex.html#SQL-CREATEINDEX-STORAGE-PARAMETERS) for more information. + +To configure a storage parameter on an index, use the following code: + +```c# +protected override void OnModelCreating(ModelBuilder modelBuilder) + => modelBuilder.Entity() + .HasIndex(b => b.Url) + .HasStorageParameter("fillfactor", 70); +``` + ## Creating indexes concurrently Creating an index can interfere with regular operation of a database. Normally PostgreSQL locks the table to be indexed against writes and performs the entire index build with a single scan of the table. Other transactions can still read the table, but if they try to insert, update, or delete rows in the table they will block until the index build is finished. This could have a severe effect if the system is a live production database. Very large tables can take many hours to be indexed, and even for smaller tables, an index build can lock out writers for periods that are unacceptably long for a production system. diff --git a/docs/modeling/table-column-naming.md b/docs/modeling/tables.md similarity index 72% rename from docs/modeling/table-column-naming.md rename to docs/modeling/tables.md index 264b535519..7a6f806d41 100644 --- a/docs/modeling/table-column-naming.md +++ b/docs/modeling/tables.md @@ -1,4 +1,6 @@ -# Table and Column Naming +# Tables + +## Naming By default, EF Core will map to tables and columns named exactly after your .NET classes and properties, so an entity type named `BlogPost` will be mapped to a PostgreSQL table called `BlogPost`. While there's nothing wrong with that, the PostgreSQL world tends towards snake_case naming instead. In addition, any upper-case letters in unquoted identifiers are automatically converted to lower-case identifiers, so the Npgsql provider generates quotes around all such identifiers. @@ -30,3 +32,14 @@ SELECT c.id, c.full_name ``` See the [plugin documentation](https://github.com/efcore/EFCore.NamingConventions) for more details, + +## Storage parameters + +PostgreSQL allows configuring tables with *storage parameters*, which can tweak storage behavior in various ways; [see the PostgreSQL documentation](https://www.postgresql.org/docs/current/sql-createtable.html#SQL-CREATETABLE-STORAGE-PARAMETERS) for more information. + +To configure a storage parameter on a table, use the following code: + +```c# +protected override void OnModelCreating(ModelBuilder modelBuilder) + => modelBuilder.Entity().HasStorageParameter("fillfactor", 70); +``` diff --git a/docs/release-notes/8.0.md b/docs/release-notes/8.0.md index 7418dbc542..b0c2e343c7 100644 --- a/docs/release-notes/8.0.md +++ b/docs/release-notes/8.0.md @@ -6,6 +6,8 @@ New features will be documented later. +* Storage parameters can now be configured on indexes ([see docs](../modeling/indexes.md)), and storage parameters are now scaffolded from existing databases for both tables and indexes. + ## Breaking changes Note: version 8.0 of the lower-level Npgsql ADO.NET driver, which is used by the EF provider, also has some breaking changes. It's recommended to read the [release notes](../../Npgsql/release-notes/8.0.md) for that as well. diff --git a/docs/toc.yml b/docs/toc.yml index 46c8cccbed..c82ed27128 100644 --- a/docs/toc.yml +++ b/docs/toc.yml @@ -24,14 +24,14 @@ href: release-notes/1.1.md - name: Creating a model items: - - name: Table and column naming - href: modeling/table-column-naming.md + - name: Tables + href: modeling/tables.md - name: Generated properties href: modeling/generated-properties.md - - name: Concurrency tokens - href: modeling/concurrency.md - name: Indexes href: modeling/indexes.md + - name: Concurrency tokens + href: modeling/concurrency.md - name: Mapping and translation items: - name: General From d15a945e9fdc8fa155421605c105296db825f84f Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Sat, 28 Oct 2023 10:43:42 +0200 Subject: [PATCH 148/207] Tweak 8.0 "not-yet-ready" note --- docs/release-notes/8.0.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/release-notes/8.0.md b/docs/release-notes/8.0.md index b0c2e343c7..6633c5d99b 100644 --- a/docs/release-notes/8.0.md +++ b/docs/release-notes/8.0.md @@ -1,6 +1,7 @@ # 8.0 Release Notes -**The below release notes and breaking changes list aren't yet complete. Check back soon for more notes.** +> [!NOTE] +> The below release notes and breaking changes list aren't yet complete. Check back soon for more notes. ## New features From 5556153aae91f64e7ca8378f21b48fba703417a5 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Mon, 13 Nov 2023 12:59:36 +0100 Subject: [PATCH 149/207] Document PG12->14 default compat mode breaking change (#313) --- docs/modeling/generated-properties.md | 16 +++------------- docs/release-notes/8.0.md | 8 ++++++++ 2 files changed, 11 insertions(+), 13 deletions(-) diff --git a/docs/modeling/generated-properties.md b/docs/modeling/generated-properties.md index 283a70ad0d..c5c4abc34d 100644 --- a/docs/modeling/generated-properties.md +++ b/docs/modeling/generated-properties.md @@ -19,10 +19,7 @@ The Npgsql EF Core provider allows you to choose which of the above you want on * *Serial*: the traditional PostgreSQL serial column. This will create the column with the `serial` datatype. Recommended only if you are using an older PostgreSQL version. * *Sequence HiLo*: See below -Prior to version 3.0, the Npgsql provider generates "serial" columns for ID columns; starting with version 3.0, it generates "identity by default" instead. In other words, when `ValueGeneratedOnAdd` is specified on a `short`, `int` or `long` property, the Npgsql provider will automatically map it to a serial or identity column. Note that EF Core will automatically recognize key properties by convention (e.g. a property called `Id` in your entity) and will implicitly set them to `ValueGeneratedOnAdd`; a standard model with ID columns should automatically get created with the appropriate column type. - -> [!CAUTION] -> Since the default strategy has changed, if you have an existing database with migrations, the the first migration created after upgrading to version 3.0 will alter your tables and convert serial columns to identity ones. This is a sensitive, one-time migration operation that should be done with care, and carefully tested before deployment to production. Changing a value generation strategy is a significant change to an existing database. +The default value generation strategy is "identity by default". In other words, when EF decides that an int property should be value generated (e.g. because it's named `Id`, or because you explicitly specified `ValueGeneratedOnAdd` on it), the Npgsql provider will automatically map it to an identity column. ### Defining the default strategy for the entire model @@ -30,14 +27,7 @@ You can easily control the value generation strategy for the entire model. For e ```c# protected override void OnModelCreating(ModelBuilder modelBuilder) - => modelBuilder.UseSerialColumns(); -``` - -Note that if you are using PostgreSQL 9.6 or older, identity columns will not work. It is recommended to place the provider in compatibility mode with your specific version - this will also affect the default value generation strategy: - -```c# -protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) - => optionsBuilder.UseNpgsql("...", o => o.SetPostgresVersion(9, 6)); + => modelBuilder.UseIdentityByDefaultColumns(); ``` ### Defining the strategy for a single property @@ -187,7 +177,7 @@ CREATE TRIGGER "UpdateTimestamp" ## Computed Columns > [!NOTE] -> This feature works only on PostgreSQL 12 or above, and was introduced in version 3.0.0 of the provider. +> This feature works only on PostgreSQL 12 or above. PostgreSQL 12 added support for [stored generated columns](https://www.postgresql.org/docs/current/ddl-generated-columns.html), and Npgsql feature supports that feature as well: diff --git a/docs/release-notes/8.0.md b/docs/release-notes/8.0.md index 6633c5d99b..1d29ff3d25 100644 --- a/docs/release-notes/8.0.md +++ b/docs/release-notes/8.0.md @@ -27,6 +27,14 @@ Existing code using the above features will start throwing exceptions after upgr Note that EF Core itself is not yet compatible with NativeAOT, and Npgsql can only be used in NativeAOT applications without EF Core. +### Default PostgreSQL compatibility mode has been bumped from 12 to 14 + +This means that the provider assumes at least PostgreSQL 14; if you're running against an older version, explicitly specify the PostgreSQL version when configuring your context: + +```csharp +optionsBuilder.UseNpgsql("", o => o.SetPostgresVersion(12, 0)) +``` + ### Obsoleted HasPostgresArrayConversion With EF 8.0 introducing first-class support for [primitive collections](https://devblogs.microsoft.com/dotnet/announcing-ef8-preview-4), the PostgreSQL driver aligned its PostgreSQL array support to use that. As a result, `HasPostgresArrayConversion` can no longer be used to configure value-converted arrays; instead, the new standard EF mechanism can be used. From 3abe6235dd743cf619980d21833e8509eac96e2e Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Sun, 19 Nov 2023 16:14:27 +0100 Subject: [PATCH 150/207] Redo JSON documentation (#315) Closes #217 --- docs/mapping/json.md | 103 +++++++++++++++++++++++++------------- docs/release-notes/8.0.md | 2 +- 2 files changed, 70 insertions(+), 35 deletions(-) diff --git a/docs/mapping/json.md b/docs/mapping/json.md index a620eae300..585e8136f5 100644 --- a/docs/mapping/json.md +++ b/docs/mapping/json.md @@ -1,15 +1,16 @@ # JSON Mapping > [!NOTE] -> EF Core 7.0 introduced support for [JSON columns](https://learn.microsoft.com/ef/core/what-is-new/ef-core-7.0/whatsnew#json-columns). Npgsql's JSON support - detailed below - is different, and has been available since version 3.0. We plan to adopt EF's JSON support in version 8.0. +> Version 8.0 of the Npgsql provider introduced support for EF's [JSON columns](https://learn.microsoft.com/ef/core/what-is-new/ef-core-7.0/whatsnew#json-columns), using `ToJson()`. That is the recommended way to map POCOs going forward. PostgreSQL has rich, built-in support for storing JSON columns and efficiently performing complex queries operations on them. Newcomers can read more about the PostgreSQL support on [the JSON types page](https://www.postgresql.org/docs/current/datatype-json.html), and on the [functions and operators page](https://www.postgresql.org/docs/current/functions-json.html). Note that the below mapping mechanisms support both the `jsonb` and `json` types, although the former is almost always preferred for efficiency reasons. The Npgsql EF Core provider allows you to map PostgreSQL JSON columns in three different ways: 1. As simple strings -2. As strongly-typed user-defined types (POCOs) -3. As [System.Text.Json](https://devblogs.microsoft.com/dotnet/try-the-new-system-text-json-apis/) DOM types (JsonDocument or JsonElement) +2. As EF owned entities +3. As System.Text.Json DOM types (JsonDocument or JsonElement, [see docs](https://learn.microsoft.com/dotnet/standard/serialization/system-text-json/use-dom#use-jsondocument)) +4. As strongly-typed user-defined types (POCOs) (deprecated) ## String mapping @@ -54,21 +55,72 @@ With string mapping, the EF Core provider will save and load properties to datab ## POCO mapping -If your column's JSON documents have a stable schema, you can map them to your own .NET types (or POCOs). The provider will use [the new System.Text.Json APIs](https://devblogs.microsoft.com/dotnet/try-the-new-system-text-json-apis/) under the hood to serialize instances to JSON documents before sending them to the database, and to deserialize documents coming from the database back. Just like EF Core can map a .NET type to rows in the table, this capability allows you to map a .NET type to a single JSON column. +If your column JSON contains documents with a stable schema, you can map them to your own .NET types (or POCOs); EF will use System.Text.Json APIs under the hood to serialize instances of your types to JSON documents before sending them to the database, and to deserialize documents coming back from the database. This effectively allows mapping an arbitrary .NET type - or object graph - to a single column in the database. -Mapping POCOs is extremely easy: simply add a property with your custom POCO type and instruct the provider to map it to JSON: +EF 7.0 introduced the "JSON Columns" feature, which maps a database JSON column via EF's "owned entity" mapping concept, using `ToJson()`. In this approach, EF fully models the types within the JSON document - just like it models regular tables and columns - and uses that information to perform better queries and updates. Full support for ToJson has been added to version 8.0 of the Npgsql EF provider. + +As an alternative, prior to version 8.0, the Npgsql EF provider has supported JSON POCO mapping by simply delegating serialization/deserialization to System.Text.Json; in this model, EF itself model the contents of the JSON document, and cannot take that structure into account for queries and updates. This approach can now be considered deprecated as it allows for less powerful mapping and supports less query types; using ToJson() is now the recommended way to map POCOs to JSON. + +### ToJson (owned entity mapping) + +Npgsql's support for `ToJson()` is fully aligned with the general EF support; see the [EF documentation for more information](https://learn.microsoft.com/ef/core/what-is-new/ef-core-7.0/whatsnew#json-columns). + +To get you started quickly, assume that we have the following Custmoer type, with a Details property that we want to map to a single JSON column in the database: + +```c# +public class Customer +{ + public int Id { get; set; } + public CustomerDetails Details { get; set; } +} + +public class CustomerDetails // Map to a JSON column in the table +{ + public string Name { get; set; } + public int Age { get; set; } + public List Orders { get; set; } +} + +public class Order // Part of the JSON column +{ + public decimal Price { get; set; } + public string ShippingAddress { get; set; } +} +``` + +To instruct EF to map CustomerDetails - and within it, Order - to a JSON column, configure it as follows: + +```c# +protected override void OnModelCreating(ModelBuilder modelBuilder) +{ + modelBuilder.Entity() + .OwnsOne(c => c.Details, d => + { + d.ToJson(); + d.OwnsMany(d => d.Orders); + }); +} +``` + +At this point you can interact with the Customer just like you would normally, and EF will seamlessly serialize and deserialize it to a JSON column in the database. You can also perform LINQ queries which reference properties inside the JSON document, and these will get translated to SQL. + +## Traditional POCO mapping (deprecated) + +Before version 8.0 introduced support for EF's ToJson (owned entity mapping), the provider had its own support for JSON POCO mapping, by simply delegating serialization/deserialization to System.Text.Json; in this model, EF itself model the contents of the JSON document, and cannot take that structure into account for queries and updates. This approach can now be considered deprecated as it allows for less powerful mapping and supports less query types; using ToJson() is now the recommended way to map POCOs to JSON. + +To use traditional POCO mapping, configure a property a mapping to map to a `jsonb` column as follows: ### [Data Annotations](#tab/data-annotations) ```c# -public class SomeEntity +public class Customer { public int Id { get; set; } [Column(TypeName = "jsonb")] - public Customer Customer { get; set; } + public CustomerDetails Details { get; set; } } -public class Customer // Mapped to a JSON column in the table +public class CustomerDetails // Mapped to a JSON column in the table { public string Name { get; set; } public int Age { get; set; } @@ -118,29 +170,9 @@ public class Order // Part of the JSON column } ``` -*** - -You can now assign a regular `Customer` instance to the property, and once you call `SaveChanges()` it will be serialized to database, producing a document such as the following: +Note that when using this mapping, only limited forms of LINQ querying is supported; it's recommended to switch to ToJson() for full LINQ querying capabilities. The querying supported by traditional POCO mapping is documented [below](#querying-traditional-and-dom). -```json -{ - "Age": 25, - "Name": "Joe", - "Orders": [ - { "OrderPrice": 9, "ShippingAddress": "Some address 1" }, - { "OrderPrice": 23, "ShippingAddress": "Some address 2" } - ] -} -``` - -Reading is just as simple: - -```c# -var someEntity = context.Entities.First(); -Console.WriteLine(someEntity.Customer.Orders[0].Price) -``` - -This provides a seamless mapping approach, and supports embedding nested types and arrays, resulting in complex JSON document schemas as shown above. This approach also allows you to traverse loaded JSON documents in a type-safe way, using regular C# syntax, and to use LINQ to query inside database JSON documents (see [Querying JSON columns](#querying-json-columns) below). +*** ## JsonDocument DOM mapping @@ -165,11 +197,16 @@ var someEntity = context.Entities.First(); Console.WriteLine(someEntity.Customer.RootElement.GetProperty("Orders")[0].GetProperty("Price").GetInt32()); ``` -## Querying JSON columns +Note that when using this mapping, only limited forms of LINQ querying is supported; [see below](#querying-traditional-and-dom) for more details. + +## Querying JSON columns (traditional JSON and DOM) + +> [!NOTE] +> The below does not apply if you are using ToJson (owned entity mapping). ToJson supports Saving and loading documents these documents wouldn't be much use without the ability to query them. You can express your queries via the same LINQ constructs you are already using in EF Core: -### [POCO Mapping](#tab/poco) +### [Classic POCO Mapping](#tab/poco) ```c# var joes = context.CustomerEntries @@ -235,5 +272,3 @@ EF.Functions.JsonTypeof(customer.GetProperty("Age")) == "number" > [!NOTE] > A section on indices will be added. In the meantime consult the PostgreSQL documentation and other guides on the Internet. - -These are early days for EF Core JSON support, and you'll likely run into some limitations. Please let us know how the current features are working for you and what you'd like to see. diff --git a/docs/release-notes/8.0.md b/docs/release-notes/8.0.md index 1d29ff3d25..40093400fa 100644 --- a/docs/release-notes/8.0.md +++ b/docs/release-notes/8.0.md @@ -19,7 +19,7 @@ Because of the NativeAOT and trimming work done for Npgsql 8.0 ([release notes]( PostgreSQL type | Default .NET type ---------------------------------------- | -------------------------- -JSON POCO mapping, JsonNode and subtypes | +JSON POCO mapping, JsonNode and subtypes | Unmapped enums, ranges, multiranges | Read PostgreSQL records as .NET tuples | From ed1429e3ec5dd91ded21f6a52fe9be80324c4185 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Sun, 19 Nov 2023 21:16:25 +0100 Subject: [PATCH 151/207] EFCore.PG 8.0 release notes (#316) --- docs/release-notes/8.0.md | 172 ++++++++++++++++++++++++++++++++++++-- 1 file changed, 167 insertions(+), 5 deletions(-) diff --git a/docs/release-notes/8.0.md b/docs/release-notes/8.0.md index 40093400fa..89c9d518fb 100644 --- a/docs/release-notes/8.0.md +++ b/docs/release-notes/8.0.md @@ -1,13 +1,175 @@ # 8.0 Release Notes -> [!NOTE] -> The below release notes and breaking changes list aren't yet complete. Check back soon for more notes. +## Full support for primitive collection querying -## New features +One of PostgreSQL unique features as a relational database is its rich support for [array types](https://www.postgresql.org/docs/current/arrays.html), which can be stored just like any other basic data type and queried. The Npgsql EF provider has supported mapping .NET arrays and Lists to PostgreSQL arrays for a very long time; however, with the introducion of [rich primitive collection support in EF itself](https://learn.microsoft.com/ef/core/what-is-new/ef-core-8.0/whatsnew#primitive-collections), Npgsql's support for arrays was extended to include full querying capabilities. -New features will be documented later. +### Column collection -* Storage parameters can now be configured on indexes ([see docs](../modeling/indexes.md)), and storage parameters are now scaffolded from existing databases for both tables and indexes. +On to the code! You can now use any LINQ operator - or chain of operators - on top of an array or list property. For example, the following queries for all blogs who have at least 3 tags starting with "x": + +```c# +var blogs = await ctx.Blogs + .Where(b => b.Tags.Count(t => t.StartsWith("x")) > 3) + .ToListAsync(); +``` + +This is now translated to the following SQL: + +```sql +SELECT b."Id", b."Tags" +FROM "Blogs" AS b +WHERE ( + SELECT count(*)::int + FROM unnest(b."Tags") AS t(value) + WHERE t.value LIKE 'x%') > 3 +``` + +Such complex translations rely on the PostgreSQL [`unnest`](https://www.postgresql.org/docs/current/functions-array.html#ARRAY-FUNCTIONS-TABLE) function, which allows expanding a PostgreSQL array to a set of rows; once that's done, the array values can be queried with regular SQL. + +We can go further, querying for all blogs whose tags - or any of their posts' tags - contains a certain value: + +```c# +var blogs = await ctx.Blogs + .Where(b => b.Tags.Union(b.Posts.SelectMany(p => p.Tags)) + .Contains("foo")) + .ToListAsync(); +``` + +This uses `unnest` both on the blog's tags on and all its posts' tags (via a lateral join), to then do a UNION On results and check whether the value is contained. + +```sql +SELECT b."Id", b."Tags" +FROM "Blogs" AS b +WHERE 'foo' IN ( + SELECT t.value + FROM unnest(b."Tags") AS t(value) + UNION + SELECT t1.value + FROM "Post" AS p + JOIN LATERAL unnest(p."Tags") AS t1(value) ON TRUE + WHERE b."Id" = p."BlogId" +) +``` + +### Parameter collections + +But that's not all... The new primitive collection support works not just on columns, but also on parameterized lists. Previously, special and limited support existed for translating Contains over a parameterized list, as follows: + +```c# +var ids = new[] { 1, 2, 3 }; + +var blogs = await ctx.Blogs + .Where(b => ids.Contains(b.Id)) + .ToListAsync(); +``` + +This has now been extended to allow composing any LINQ operator. For example, the following query queries for any blogs which have at least one tag, where that tag starts with a list of possible prefixes: + +```c# +var prefixes = new[] { "f", "b" }; + +var blogs = await ctx.Blogs + .Where(b => prefixes.Any(p => b.Tags.Any(t => t.StartsWith(p)))) + .ToListAsync(); +``` + +Complex, I know! This translates to the following SQL: + +```sql +SELECT b."Id", b."Tags" +FROM "Blogs" AS b +WHERE EXISTS ( + SELECT 1 + FROM unnest(@__prefixes_0) AS p(value) + WHERE EXISTS ( + SELECT 1 + FROM unnest(b."Tags") AS t(value) + WHERE p.value IS NOT NULL AND left(t.value, length(p.value)) = p.value)) +``` + +Note the two usages of `unnest` here: one is used to expand the Tags column, whereas the other is used to expand the `@__prefixes_0` array parameter that EF sends. All this machinery works together to make your LINQ query execute correctly. + +### Inline collections + +Finally, support was added to *inline collections*, which are collections specified *inside* the query. For example, let's say that the list of tag prefixes in the previous query were always the same; in that case, we'd inline the prefixes variable as follows: + +```c# +var blogs = await ctx.Blogs + .Where(b => new[] { "f", "b" }.Any(p => b.Tags.Any(t => t.StartsWith(p)))) + .ToListAsync(); +``` + +This translates to the following: + +```sql + SELECT b."Id", b."Tags" + FROM "Blogs" AS b + WHERE EXISTS ( + SELECT 1 + FROM (VALUES ('f'::text), ('b')) AS v("Value") + WHERE EXISTS ( + SELECT 1 + FROM unnest(b."Tags") AS t(value) + WHERE left(t.value, length(v."Value")) = v."Value")) +``` + +Note that the `unnest` over the parameter has been replaced with a standard SQL `VALUES` construct, which allows constructing a set of rows inline, inside the query. + +### More information + +Exciting stuff! We hope this helps you use LINQ to model and better interact with your database. + +* [The primitive collection section](https://learn.microsoft.com/ef/core/what-is-new/ef-core-8.0/whatsnew#primitive-collections) in the EF 8.0 What's New page. +* [.NET Blog post on primitive collections](https://devblogs.microsoft.com/dotnet/announcing-ef8-preview-4/) +* [PostgreSQL-specific information on primitive collections](https://www.roji.org/queryable-pg-arrays-in-ef8), including some specialized translations done for PostgreSQL. + +## EF JSON support via ToJson() + +Version 8.0 also brings support for EF7's [JSON columns](https://learn.microsoft.com/ef/core/what-is-new/ef-core-7.0/whatsnew#json-columns) feature (ToJson), which allows mapping JSON columns via owned entity types. While the Npgsql EF provider has had POCO JSON mapping for a very long time, the full modeling of the new ToJson() allows for a more powerful mapping strategy, with more query and update features. ToJson is the recommended way to map JSON going forward. + +You can read more on ToJson in the [Npgsql JSON doc page](../mapping/json.md), and in the [EF7 what's new docs](https://learn.microsoft.com/ef/core/what-is-new/ef-core-7.0/whatsnew#json-columns). Compared to the traditional Npgsql-specific POCO approach, a much wider range of LINQ queries can now be translated. For example, you can now compose LINQ operators over collections within JSON documents: + +```c# +var blogs = await ctx.Customers + .Where(b => b.Details.Orders.Any(o => o.Price > 8)) + .ToListAsync(); +``` + +Note that this composes a LINQ operator - Any - on top of Orders, which is a list nested inside a JSON document. This translates to the following SQL: + +```sql +SELECT c."Id", c."Details" +FROM "Customers" AS c +WHERE EXISTS ( + SELECT 1 + FROM ROWS FROM (jsonb_to_recordset(c."Details" -> 'Orders') AS ( + "Price" numeric, + "ShippingAddress" text + )) AS o + WHERE o."Price" > 8.0) +``` + +Note the [`jsonb_to_recordset`](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-PROCESSING-TABLE) function, which drills into the JSON document, finds the Orders property, and then expands that out to a set of rows, which can then be queried via regular SQL. + +Similarly, updates via EF's SaveChanges() are better, and can leverage *partial updating* to only patch the part of the JSON document which has changed. For example, let's assume that we load some customer with a JSON column, and change a single property within that JSON data: + +```c# +var customer = await ctx.Customers.SingleAsync(c => c.Details.Name == "Foo"); +customer.Details.Name = "Bar"; +await ctx.SaveChangesAsync(); +``` + +Rather than needlessly sending the entire JSON document back to PostgreSQL, the EF provider uses the [`jsonb_set`](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-PROCESSING-TABLE) function to patch the specific property which changed, which is more efficient: + +```sql +UPDATE "Customers" SET "Details" = jsonb_set("Details", '{Name}', @p0) +WHERE "Id" = @p1; +``` + +## Other new features + +Version 8.0 contains many other smaller features and bug fixes, both on the EF side and on the Npgsql provider side. [See the 8.0.0 milestone](https://github.com/npgsql/efcore.pg/milestone/53?closed=1) for the full list of Npgsql EF provider issues. ## Breaking changes From 23f1773245ec2dda115698958e86a6fcd54a26c2 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Sun, 19 Nov 2023 21:29:26 +0100 Subject: [PATCH 152/207] Document more breaking changes (#317) --- docs/release-notes/8.0.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/release-notes/8.0.md b/docs/release-notes/8.0.md index 89c9d518fb..2038147f06 100644 --- a/docs/release-notes/8.0.md +++ b/docs/release-notes/8.0.md @@ -223,3 +223,7 @@ class MyConverter : ValueConverter } } ``` + +### `cidr` now maps to `NpgsqlCidr` instead of `ValueTuple` + +As part of improving Npgsql's support for the PostgreSQL network mappings, the PostgreSQL `cidr` type now maps to the newly-introduced , and can no longer be mapped to `ValueTuple`. From f6743107aaecf0a14eb5413cd5363977ebf90697 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Tue, 21 Nov 2023 01:56:14 +0100 Subject: [PATCH 153/207] Update notes to reflect that 8.0 was released --- docs/release-notes/8.0.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/release-notes/8.0.md b/docs/release-notes/8.0.md index 2038147f06..7c547a0b80 100644 --- a/docs/release-notes/8.0.md +++ b/docs/release-notes/8.0.md @@ -1,5 +1,7 @@ # 8.0 Release Notes +Npgsql.EntityFrameworkCore.PostgreSQL version 8.0 is out and available on [nuget.org](https://www.nuget.org/packages/Npgsql.EntityFrameworkCore.PostgreSQL). + ## Full support for primitive collection querying One of PostgreSQL unique features as a relational database is its rich support for [array types](https://www.postgresql.org/docs/current/arrays.html), which can be stored just like any other basic data type and queried. The Npgsql EF provider has supported mapping .NET arrays and Lists to PostgreSQL arrays for a very long time; however, with the introducion of [rich primitive collection support in EF itself](https://learn.microsoft.com/ef/core/what-is-new/ef-core-8.0/whatsnew#primitive-collections), Npgsql's support for arrays was extended to include full querying capabilities. From 638ff72c2955bedece1b6ba59958cd2ed949a9f1 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Tue, 21 Nov 2023 02:03:57 +0100 Subject: [PATCH 154/207] Typo --- docs/release-notes/8.0.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/release-notes/8.0.md b/docs/release-notes/8.0.md index 7c547a0b80..f9f2729c28 100644 --- a/docs/release-notes/8.0.md +++ b/docs/release-notes/8.0.md @@ -6,7 +6,7 @@ Npgsql.EntityFrameworkCore.PostgreSQL version 8.0 is out and available on [nuget One of PostgreSQL unique features as a relational database is its rich support for [array types](https://www.postgresql.org/docs/current/arrays.html), which can be stored just like any other basic data type and queried. The Npgsql EF provider has supported mapping .NET arrays and Lists to PostgreSQL arrays for a very long time; however, with the introducion of [rich primitive collection support in EF itself](https://learn.microsoft.com/ef/core/what-is-new/ef-core-8.0/whatsnew#primitive-collections), Npgsql's support for arrays was extended to include full querying capabilities. -### Column collection +### Column collections On to the code! You can now use any LINQ operator - or chain of operators - on top of an array or list property. For example, the following queries for all blogs who have at least 3 tags starting with "x": From af470e09db9eaf047caa5c808581b45aa80e5d14 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Tue, 21 Nov 2023 02:05:17 +0100 Subject: [PATCH 155/207] Add primitive collection context --- docs/release-notes/8.0.md | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/docs/release-notes/8.0.md b/docs/release-notes/8.0.md index f9f2729c28..e83be81ed1 100644 --- a/docs/release-notes/8.0.md +++ b/docs/release-notes/8.0.md @@ -8,9 +8,15 @@ One of PostgreSQL unique features as a relational database is its rich support f ### Column collections -On to the code! You can now use any LINQ operator - or chain of operators - on top of an array or list property. For example, the following queries for all blogs who have at least 3 tags starting with "x": +On to the code! You can now use any LINQ operator - or chain of operators - on top of a primitive array or list property. For example, the following queries for all blogs who have at least 3 tags starting with "x": ```c# +class Blog +{ + ... + public List Tags { get; set; } +} + var blogs = await ctx.Blogs .Where(b => b.Tags.Count(t => t.StartsWith("x")) > 3) .ToListAsync(); From 9c1623aebfac63b1f8bdf668eca75a979b2fb1ea Mon Sep 17 00:00:00 2001 From: Brar Piening Date: Tue, 21 Nov 2023 11:57:43 +0100 Subject: [PATCH 156/207] Update contributors in release notes. (#321) Patch contributions without an assigned issue are still missing. This will follow in a separate PR after updating the generator program at some point. --- docs/release-notes/3.1.md | 6 ++++ docs/release-notes/5.0.md | 67 ++++++++++++++++++++++++++++++++------ docs/release-notes/6.0.md | 68 +++++++++++++++++++++++++++++++++++++++ docs/release-notes/7.0.md | 36 +++++++++++++++++++++ docs/release-notes/8.0.md | 11 +++++++ 5 files changed, 178 insertions(+), 10 deletions(-) diff --git a/docs/release-notes/3.1.md b/docs/release-notes/3.1.md index b8f3e9e272..647aae5024 100644 --- a/docs/release-notes/3.1.md +++ b/docs/release-notes/3.1.md @@ -52,6 +52,12 @@ More information is available in [the page about generated properties](../modeli Thank you very much to the following people who have contributed to the individual 3.x releases. +### [Milestone 3.1.11](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A3.1.11) + +| Contributor | Assigned issues | +| -------------------------------- | -----------------------------------------------------------------------------------------------------------:| +| [@roji](https://github.com/roji) | [5](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A3.1.11+is%3Aclosed+assignee%3Aroji) | + ### [Milestone 3.1.7](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.1.7) Contributor | Assigned issues diff --git a/docs/release-notes/5.0.md b/docs/release-notes/5.0.md index 779c6a2a17..0a78c5cd3c 100644 --- a/docs/release-notes/5.0.md +++ b/docs/release-notes/5.0.md @@ -53,13 +53,60 @@ Previously, when `IsCreatedConcurrently` was used to configure an index without A big thank you to all the following people who contributed to the 5.0 release! -### [Milestone 5.0.0](https://github.com/npgsql/EFCore.PG/issues?q=milestone%3A5.0.0+) - -Contributor | Assigned issues ----------------------------------------------- | ----------------:| -[@artfulsage](https://github.com/artfulsage) | [1](https://github.com/npgsql/EFCore.PG/issues?q=milestone%3A5.0.0+assignee%3Aartfulsage+) -[@cloudlucky](https://github.com/cloudlucky) | [1](https://github.com/npgsql/EFCore.PG/issues?q=milestone%3A5.0.0+assignee%3Acloudlucky+) -[@plamen-i](https://github.com/plamen-i) | [1](https://github.com/npgsql/EFCore.PG/issues?q=milestone%3A5.0.0+assignee%3Aplamen-i) -[@Quogu](https://github.com/Quogu) | [1](https://github.com/npgsql/EFCore.PG/issues?q=milestone%3A5.0.0+assignee%3AQuogu+) -[@YohDeadfall](https://github.com/yohdeadfall) | [1](https://github.com/npgsql/EFCore.PG/issues?q=milestone%3A5.0.0+assignee%3Ayohdeadfall+) -[@roji](https://github.com/roji) | [45](https://github.com/npgsql/EFCore.PG/issues?q=milestone%3A5.0.0+assignee%3Aroji) +### [Milestone 5.0.10](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A5.0.10) + +| Contributor | Assigned issues | +| ---------------------------------------------- | ------------------------------------------------------------------------------------------------------------------:| +| [@roji](https://github.com/roji) | [3](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A5.0.10+is%3Aclosed+assignee%3Aroji) | +| [@dmitrynovik](https://github.com/dmitrynovik) | [1](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A5.0.10+is%3Aclosed+assignee%3Admitrynovik) | + +### [Milestone 5.0.7](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A5.0.7) + +| Contributor | Assigned issues | +| ---------------------------------------- | --------------------------------------------------------------------------------------------------------------:| +| [@roji](https://github.com/roji) | [5](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A5.0.7+is%3Aclosed+assignee%3Aroji) | +| [@nathan-c](https://github.com/nathan-c) | [1](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A5.0.7+is%3Aclosed+assignee%3Anathan-c) | + +### [Milestone 5.0.6](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A5.0.6) + +| Contributor | Assigned issues | +| ------------------------------------ | ------------------------------------------------------------------------------------------------------------:| +| [@roji](https://github.com/roji) | [2](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A5.0.6+is%3Aclosed+assignee%3Aroji) | +| [@kakone](https://github.com/kakone) | [1](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A5.0.6+is%3Aclosed+assignee%3Akakone) | + +### [Milestone 5.0.5.1](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A5.0.5.1) + +| Contributor | Assigned issues | +| ---------------------------------------- | ----------------------------------------------------------------------------------------------------------------:| +| [@fsibilla](https://github.com/fsibilla) | [1](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A5.0.5.1+is%3Aclosed+assignee%3Afsibilla) | +| [@roji](https://github.com/roji) | [1](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A5.0.5.1+is%3Aclosed+assignee%3Aroji) | + +### [Milestone 5.0.5](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A5.0.5) + +| Contributor | Assigned issues | +| ------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------:| +| [@roji](https://github.com/roji) | [8](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A5.0.5+is%3Aclosed+assignee%3Aroji) | +| [@DanielAdolfsson](https://github.com/DanielAdolfsson) | [1](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A5.0.5+is%3Aclosed+assignee%3ADanielAdolfsson) | + +### [Milestone 5.0.2](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A5.0.2) + +| Contributor | Assigned issues | +| -------------------------------- | ----------------------------------------------------------------------------------------------------------:| +| [@roji](https://github.com/roji) | [6](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A5.0.2+is%3Aclosed+assignee%3Aroji) | + +### [Milestone 5.0.1](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A5.0.1) + +| Contributor | Assigned issues | +| ------------------------------------ | ------------------------------------------------------------------------------------------------------------:| +| [@roji](https://github.com/roji) | [4](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A5.0.1+is%3Aclosed+assignee%3Aroji) | +| [@akilin](https://github.com/akilin) | [1](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A5.0.1+is%3Aclosed+assignee%3Aakilin) | + +### [Milestone 5.0.0](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A5.0.0) + +| Contributor | Assigned issues | +| -------------------------------------------- | ----------------------------------------------------------------------------------------------------------------:| +| [@roji](https://github.com/roji) | [50](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A5.0.0+is%3Aclosed+assignee%3Aroji) | +| [@artfulsage](https://github.com/artfulsage) | [1](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A5.0.0+is%3Aclosed+assignee%3Aartfulsage) | +| [@cloudlucky](https://github.com/cloudlucky) | [1](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A5.0.0+is%3Aclosed+assignee%3Acloudlucky) | +| [@plamen-i](https://github.com/plamen-i) | [1](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A5.0.0+is%3Aclosed+assignee%3Aplamen-i) | +| [@Quogu](https://github.com/Quogu) | [1](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A5.0.0+is%3Aclosed+assignee%3AQuogu) | diff --git a/docs/release-notes/6.0.md b/docs/release-notes/6.0.md index ee9aee910a..124d86aaa3 100644 --- a/docs/release-notes/6.0.md +++ b/docs/release-notes/6.0.md @@ -191,3 +191,71 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) ### Trigrams and FuzzyStringMatch plugins are now built-in The Npgsql.EntityFrameworkCore.PostgreSQL.Trigrams and Npgsql.EntityFrameworkCore.PostgreSQL.FuzzyStringMatch plugins have been integrated into the main provider; as a result, there are no 6.0 versions of these nuget packages - simply remove the package references from your project when upgrading to 6.0.0. + +## Contributors + +A big thank you to all the following people who contributed to the 5.0 release! + +### [Milestone 6.0.8](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A6.0.8) + +| Contributor | Assigned issues | +| -------------------------------- | ----------------------------------------------------------------------------------------------------------:| +| [@roji](https://github.com/roji) | [3](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A6.0.8+is%3Aclosed+assignee%3Aroji) | + +### [Milestone 6.0.7](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A6.0.7) + +| Contributor | Assigned issues | +| -------------------------------- | ----------------------------------------------------------------------------------------------------------:| +| [@roji](https://github.com/roji) | [5](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A6.0.7+is%3Aclosed+assignee%3Aroji) | + +### [Milestone 6.0.6](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A6.0.6) + +| Contributor | Assigned issues | +| -------------------------------- | ----------------------------------------------------------------------------------------------------------:| +| [@roji](https://github.com/roji) | [2](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A6.0.6+is%3Aclosed+assignee%3Aroji) | + +### [Milestone 6.0.5](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A6.0.5) + +| Contributor | Assigned issues | +| -------------------------------- | ----------------------------------------------------------------------------------------------------------:| +| [@roji](https://github.com/roji) | [5](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A6.0.5+is%3Aclosed+assignee%3Aroji) | + +### [Milestone 6.0.4](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A6.0.4) + +| Contributor | Assigned issues | +| ---------------------------------------- | --------------------------------------------------------------------------------------------------------------:| +| [@roji](https://github.com/roji) | [6](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A6.0.4+is%3Aclosed+assignee%3Aroji) | +| [@kourosko](https://github.com/kourosko) | [1](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A6.0.4+is%3Aclosed+assignee%3Akourosko) | + +### [Milestone 6.0.3](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A6.0.3) + +| Contributor | Assigned issues | +| -------------------------------------- | -------------------------------------------------------------------------------------------------------------:| +| [@roji](https://github.com/roji) | [8](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A6.0.3+is%3Aclosed+assignee%3Aroji) | +| [@rus-art](https://github.com/rus-art) | [1](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A6.0.3+is%3Aclosed+assignee%3Arus-art) | + +### [Milestone 6.0.2](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A6.0.2) + +| Contributor | Assigned issues | +| -------------------------------- | ----------------------------------------------------------------------------------------------------------:| +| [@roji](https://github.com/roji) | [4](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A6.0.2+is%3Aclosed+assignee%3Aroji) | + +### [Milestone 6.0.1](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A6.0.1) + +| Contributor | Assigned issues | +| ---------------------------------------- | --------------------------------------------------------------------------------------------------------------:| +| [@roji](https://github.com/roji) | [5](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A6.0.1+is%3Aclosed+assignee%3Aroji) | +| [@Brar](https://github.com/Brar) | [1](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A6.0.1+is%3Aclosed+assignee%3ABrar) | +| [@vonzshik](https://github.com/vonzshik) | [1](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A6.0.1+is%3Aclosed+assignee%3Avonzshik) | + +### [Milestone 6.0.0](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A6.0.0) + +| Contributor | Assigned issues | +| ------------------------------------------ | ---------------------------------------------------------------------------------------------------------------:| +| [@roji](https://github.com/roji) | [56](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A6.0.0+is%3Aclosed+assignee%3Aroji) | +| [@vonzshik](https://github.com/vonzshik) | [2](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A6.0.0+is%3Aclosed+assignee%3Avonzshik) | +| [@arontsang](https://github.com/arontsang) | [1](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A6.0.0+is%3Aclosed+assignee%3Aarontsang) | +| [@Isitar](https://github.com/Isitar) | [1](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A6.0.0+is%3Aclosed+assignee%3AIsitar) | +| [@kislovs](https://github.com/kislovs) | [1](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A6.0.0+is%3Aclosed+assignee%3Akislovs) | +| [@pafrench](https://github.com/pafrench) | [1](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A6.0.0+is%3Aclosed+assignee%3Apafrench) | +| [@tiborfsk](https://github.com/tiborfsk) | [1](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A6.0.0+is%3Aclosed+assignee%3Atiborfsk) | diff --git a/docs/release-notes/7.0.md b/docs/release-notes/7.0.md index bd7e691e3b..41577a9e93 100644 --- a/docs/release-notes/7.0.md +++ b/docs/release-notes/7.0.md @@ -101,3 +101,39 @@ protected override void ConfigureConventions(ModelConfigurationBuilder configura configurationBuilder.Properties().UseCollation(""); } ``` + +## Contributors + +A big thank you to all the following people who contributed to the 5.0 release! + +### [Milestone 7.0.11](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A7.0.11) + +| Contributor | Assigned issues | +| -------------------------------- | -----------------------------------------------------------------------------------------------------------:| +| [@roji](https://github.com/roji) | [1](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A7.0.11+is%3Aclosed+assignee%3Aroji) | + +### [Milestone 7.0.4](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A7.0.4) + +| Contributor | Assigned issues | +| -------------------------------- | ----------------------------------------------------------------------------------------------------------:| +| [@roji](https://github.com/roji) | [7](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A7.0.4+is%3Aclosed+assignee%3Aroji) | + +### [Milestone 7.0.3](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A7.0.3) + +| Contributor | Assigned issues | +| ------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------:| +| [@jhartmann123](https://github.com/jhartmann123) | [1](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A7.0.3+is%3Aclosed+assignee%3Ajhartmann123) | +| [@roji](https://github.com/roji) | [1](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A7.0.3+is%3Aclosed+assignee%3Aroji) | + +### [Milestone 7.0.1](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A7.0.1) + +| Contributor | Assigned issues | +| -------------------------------- | ----------------------------------------------------------------------------------------------------------:| +| [@roji](https://github.com/roji) | [3](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A7.0.1+is%3Aclosed+assignee%3Aroji) | + +### [Milestone 7.0.0](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A7.0.0) + +| Contributor | Assigned issues | +| ---------------------------------------- | --------------------------------------------------------------------------------------------------------------:| +| [@roji](https://github.com/roji) | [35](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A7.0.0+is%3Aclosed+assignee%3Aroji) | +| [@midgleyc](https://github.com/midgleyc) | [1](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A7.0.0+is%3Aclosed+assignee%3Amidgleyc) | diff --git a/docs/release-notes/8.0.md b/docs/release-notes/8.0.md index e83be81ed1..06e1c94da4 100644 --- a/docs/release-notes/8.0.md +++ b/docs/release-notes/8.0.md @@ -235,3 +235,14 @@ class MyConverter : ValueConverter ### `cidr` now maps to `NpgsqlCidr` instead of `ValueTuple` As part of improving Npgsql's support for the PostgreSQL network mappings, the PostgreSQL `cidr` type now maps to the newly-introduced , and can no longer be mapped to `ValueTuple`. + +## Contributors + +A big thank you to all the following people who contributed to the 5.0 release! + +### [Milestone 8.0.0](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A8.0.0) + +| Contributor | Assigned issues | +| ---------------------------------- | -----------------------------------------------------------------------------------------------------------:| +| [@roji](https://github.com/roji) | [34](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A8.0.0+is%3Aclosed+assignee%3Aroji) | +| [@zpaks](https://github.com/zpaks) | [1](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A8.0.0+is%3Aclosed+assignee%3Azpaks) | From d4def9c78f02734933a0989ace5c0978a937e98d Mon Sep 17 00:00:00 2001 From: Brar Piening Date: Tue, 21 Nov 2023 13:09:06 +0100 Subject: [PATCH 157/207] Fix release tags in the thank you statements --- docs/release-notes/6.0.md | 2 +- docs/release-notes/7.0.md | 2 +- docs/release-notes/8.0.md | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/release-notes/6.0.md b/docs/release-notes/6.0.md index 124d86aaa3..908aa0f9ca 100644 --- a/docs/release-notes/6.0.md +++ b/docs/release-notes/6.0.md @@ -194,7 +194,7 @@ The Npgsql.EntityFrameworkCore.PostgreSQL.Trigrams and Npgsql.EntityFrameworkCor ## Contributors -A big thank you to all the following people who contributed to the 5.0 release! +A big thank you to all the following people who contributed to the 6.0 release! ### [Milestone 6.0.8](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A6.0.8) diff --git a/docs/release-notes/7.0.md b/docs/release-notes/7.0.md index 41577a9e93..275d81be1c 100644 --- a/docs/release-notes/7.0.md +++ b/docs/release-notes/7.0.md @@ -104,7 +104,7 @@ protected override void ConfigureConventions(ModelConfigurationBuilder configura ## Contributors -A big thank you to all the following people who contributed to the 5.0 release! +A big thank you to all the following people who contributed to the 7.0 release! ### [Milestone 7.0.11](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A7.0.11) diff --git a/docs/release-notes/8.0.md b/docs/release-notes/8.0.md index 06e1c94da4..596457b3e9 100644 --- a/docs/release-notes/8.0.md +++ b/docs/release-notes/8.0.md @@ -238,7 +238,7 @@ As part of improving Npgsql's support for the PostgreSQL network mappings, the P ## Contributors -A big thank you to all the following people who contributed to the 5.0 release! +A big thank you to all the following people who contributed to the 8.0 release! ### [Milestone 8.0.0](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A8.0.0) From f29fad8d3d4b04983deb3439b2b15f0919e90c97 Mon Sep 17 00:00:00 2001 From: Igor Postanogov Date: Thu, 7 Dec 2023 12:56:16 +0500 Subject: [PATCH 158/207] docs: Fix typo in JSON (#325) --- docs/mapping/json.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/mapping/json.md b/docs/mapping/json.md index 585e8136f5..465e170b4d 100644 --- a/docs/mapping/json.md +++ b/docs/mapping/json.md @@ -65,7 +65,7 @@ As an alternative, prior to version 8.0, the Npgsql EF provider has supported JS Npgsql's support for `ToJson()` is fully aligned with the general EF support; see the [EF documentation for more information](https://learn.microsoft.com/ef/core/what-is-new/ef-core-7.0/whatsnew#json-columns). -To get you started quickly, assume that we have the following Custmoer type, with a Details property that we want to map to a single JSON column in the database: +To get you started quickly, assume that we have the following Customer type, with a Details property that we want to map to a single JSON column in the database: ```c# public class Customer From 9987db053a5ec87d47701a165e545a4d334d8d57 Mon Sep 17 00:00:00 2001 From: Daniel Haas <78215988+haas-daniel@users.noreply.github.com> Date: Fri, 8 Dec 2023 23:03:11 +0100 Subject: [PATCH 159/207] Escape pipes in string translations doc (#326) This commit fixes text appearing in wrong columns caused by not escaped pipe characters. --- docs/mapping/translations.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/mapping/translations.md b/docs/mapping/translations.md index 8234bc27d3..3665a6eb75 100644 --- a/docs/mapping/translations.md +++ b/docs/mapping/translations.md @@ -45,8 +45,8 @@ Regex.IsMatch(stringValue, "^A+", regexOptions) | [stringValue ~ ' string.Join(", ", a, b) | [concat_ws(', ', a, b)](https://www.postgresql.org/docs/current/functions-string.html#FUNCTIONS-STRING-OTHER) | Added in 7.0 (previously array_to_string) string.Join(", ", array) | [array_to_string(array, ', ', '')](https://www.postgresql.org/docs/current/functions-array.html#ARRAY-FUNCTIONS-TABLE) string.Join(", ", agg_strings) | [string_agg(agg_strings, ', ')](https://www.postgresql.org/docs/current/functions-aggregate.html#FUNCTIONS-AGGREGATE-TABLE) | Added in 7.0, see [Aggregate functions](#aggregate-functions). -EF.Functions.StringToArray(s, "|") | [string_agg(s, '\|')](https://www.postgresql.org/docs/current/functions-string.html#FUNCTION-STRING-TO-ARRAY) | Added in 8.0 -EF.Functions.StringToArray(s, "|", "FOO") | [string_agg(s, '\|', 'FOO')](https://www.postgresql.org/docs/current/functions-string.html#FUNCTION-STRING-TO-ARRAY) | Added in 8.0 +EF.Functions.StringToArray(s, "\|") | [string_agg(s, '\|')](https://www.postgresql.org/docs/current/functions-string.html#FUNCTION-STRING-TO-ARRAY) | Added in 8.0 +EF.Functions.StringToArray(s, "\|", "FOO") | [string_agg(s, '\|', 'FOO')](https://www.postgresql.org/docs/current/functions-string.html#FUNCTION-STRING-TO-ARRAY) | Added in 8.0 ## Date and time functions From dd681738b10845145dfdd368af10ca9878c3dda7 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Sat, 11 May 2024 23:31:14 +0200 Subject: [PATCH 160/207] Update string.Contains() translation --- docs/mapping/translations.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/mapping/translations.md b/docs/mapping/translations.md index 3665a6eb75..9e8f851454 100644 --- a/docs/mapping/translations.md +++ b/docs/mapping/translations.md @@ -18,7 +18,7 @@ string.Concat(str0, str1) | str0 \|\| str1 string.IsNullOrEmpty(value) | value IS NULL OR value = '' string.IsNullOrWhiteSpace(value) | value IS NULL OR btrim(value, E' \t\n\r') = '' stringValue.CompareTo(strB) | CASE WHEN stringValue = strB THEN 0 ... END -stringValue.Contains(value) | strpos(stringValue, value) > 0 +stringValue.Contains(value) | stringValue LIKE %value% stringValue.EndsWith(value) | stringValue LIKE '%' \|\| value stringValue.FirstOrDefault() | substr(stringValue, 1, 1) | Added in 5.0 stringValue.IndexOf(value) | strpos(stringValue, value) - 1 From f31e495dc1ebd3ce8b268e183df5d85e9724e6f9 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Sun, 1 Sep 2024 18:59:00 +0200 Subject: [PATCH 161/207] Docs related to version 7 GUID generation (#349) See https://github.com/npgsql/efcore.pg/pull/3249 --- docs/modeling/generated-properties.md | 6 +++--- docs/release-notes/9.0.md | 25 +++++++++++++++++++++++++ 2 files changed, 28 insertions(+), 3 deletions(-) create mode 100644 docs/release-notes/9.0.md diff --git a/docs/modeling/generated-properties.md b/docs/modeling/generated-properties.md index c5c4abc34d..c359dc7a3c 100644 --- a/docs/modeling/generated-properties.md +++ b/docs/modeling/generated-properties.md @@ -92,9 +92,9 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) ## GUID/UUID Generation -By default, for GUID key properties, a random GUID is generated client-side by the EF provider and sent to the database. +By default, for GUID key properties, a GUID is generated client-side by the EF provider and sent to the database. From version 9.0 and onwards, these GUIDs are sequential (version 7), which are more optimized for database indexes (before version 9.0, these GUIDs were random). -To generate GUID's client-side for non-key properties, configure them as follows: +To have the provider generate GUIDs client-side for **non-key** properties, configure them as follows: ```c# protected override void OnModelCreating(ModelBuilder modelBuilder) @@ -102,7 +102,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) modelBuilder .Entity() .Property(b => b.SomeGuidProperty) - .HasValueGenerator(); + .HasValueGenerator(); } ``` diff --git a/docs/release-notes/9.0.md b/docs/release-notes/9.0.md new file mode 100644 index 0000000000..737e7f1400 --- /dev/null +++ b/docs/release-notes/9.0.md @@ -0,0 +1,25 @@ +# 9.0 Release Notes + +Npgsql.EntityFrameworkCore.PostgreSQL version 9.0 is under development; previews are available on [nuget.org](https://www.nuget.org/packages/Npgsql.EntityFrameworkCore.PostgreSQL). + +## UUIDv7 GUIDs are generated by default + +When your entity types have a `Guid` key, EF Core by default generates key values for new entities client-side - in .NET - before inserting those entity types to the database; this can be better for performance in some situations. Before version 9.0, the provider generated random GUIDs (version 4) by calling the .NET [`Guid.NewGuid()`](https://learn.microsoft.com/en-us/dotnet/api/system.guid.newguid?view=net-8.0#system-guid-newguid) function. Unfortunately, random GUIDs aren't ideal for database indexing and can cause performance issues. + +Version 9.0 of the provider now generates the recently standardized version 7 GUIDs, which is a sequential GUID type that's more appropriate for database indexes and improves their performance. This new behavior is by default and will take effect simply by upgrading the provider version. + +See [this post](https://www.cybertec-postgresql.com/en/unexpected-downsides-of-uuid-keys-in-postgresql) for more details and performance numbers on random vs. sequential GUIDs. + +Thanks to [@ChrisJollyAU](https://github.com/ChrisJollyAU) and [@Timovzl](https://github.com/Timovzl) for contributing this improvement! + +## Contributors + +A big thank you to all the following people who contributed to the 9.0 release! + +### [Milestone 9.0.0](https://github.com/npgsql/efcore.pg/milestone/61?closed=1) + +Contributor | Assigned issues +------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------ +[@roji](https://github.com/roji) | [34](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A8.0.0+is%3Aclosed+assignee%3Aroji) +[@ChrisJollyAU](https://github.com/ChrisJollyAU) | [1](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A8.0.0+is%3Aclosed+assignee%3AChrisJollyAU) +[@Timovzl](https://github.com/Timovzl) | [1](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A8.0.0+is%3Aclosed+assignee%3ATimovzl) From 81baa0ca7c47e1cccfb9019287cd3e810d5f3f8c Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Fri, 13 Sep 2024 19:27:18 +0200 Subject: [PATCH 162/207] Docs on the new enum/plugin config (#352) Closes #351 --- docs/mapping/enum.md | 82 ++++++++++++++++++++++++--------------- docs/mapping/nodatime.md | 35 ++++++++++------- docs/mapping/nts.md | 35 ++++++++++------- docs/release-notes/9.0.md | 38 +++++++++++++++++- 4 files changed, 131 insertions(+), 59 deletions(-) diff --git a/docs/mapping/enum.md b/docs/mapping/enum.md index c09a5a8754..f52f0d25da 100644 --- a/docs/mapping/enum.md +++ b/docs/mapping/enum.md @@ -4,46 +4,66 @@ By default, any enum properties in your model will be mapped to database integer However, the Npgsql provider also allows you to map your CLR enums to [database enum types](https://www.postgresql.org/docs/current/static/datatype-enum.html). This option, unique to PostgreSQL, provides the best of both worlds: the enum is internally stored in the database as a number (minimal storage), but is handled like a string (more usable, no need to remember numeric values) and has type safety. -## Creating your database enum +## Setting up your enum with EF -First, you must specify the PostgreSQL enum type on your model, just like you would with tables, sequences or other databases objects: +> [!NOTE] +> Enum mapping has changed considerably in EF 9.0. + +If you're using EF 9.0 or above, simply call `MapEnum` inside your `UseNpgsql` invocation. + +### [With a connection string](#tab/with-connection-string) + +If you're passing a connection string to `UseNpgsql`, simply add the `MapEnum` call as follows: ```c# -protected override void OnModelCreating(ModelBuilder builder) - => builder.HasPostgresEnum(); +builder.Services.AddDbContext(options => options.UseNpgsql( + "", + o => o.MapEnum("mood"))); ``` -This causes the EF Core provider to create your enum type, `mood`, with two labels: `happy` and `sad`. This will cause the appropriate migration to be created. +This configures all aspects of Npgsql to use your `Mood` enum - both at the EF and the lower-level Npgsql layer - and ensures that the enum is created in the database in EF migrations. + +### [With an external NpgsqlDataSource](#tab/with-datasource) -If you are using `context.Database.Migrate()` to create your enums, you need to instruct Npgsql to reload all types after applying your migrations: +If you're creating an external NpgsqlDataSource and passing it to `UseNpgsql`, you must make sure to map your enum on that data independently of the EF-level setup: ```c# -await context.Database.MigrateAsync(token); +var dataSourceBuilder = new NpgsqlDataSourceBuilder(""); +dataSourceBuilder.MapEnum(); +var dataSource = dataSourceBuilder.Build(); -if (context.Database.GetDbConnection() is NpgsqlConnection npgsqlConnection) -{ - await npgsqlConnection.OpenAsync(token); - try - { - await npgsqlConnection.ReloadTypesAsync(); - } - finally - { - await npgsqlConnection.CloseAsync(); - } -} +builder.Services.AddDbContext(options => options.UseNpgsql( + dataSource, + o => o.MapEnum("mood"))); +``` + +*** + +### Older EF versions + +On versions of EF prior to 9.0, enum setup is more involved and consists of several steps; enum mapping has to be done at the lower-level Npgsql layer, and also requires explicit configuration in the EF model for creation in the database via migrations. + +#### Creating your database enum + +First, you must specify the PostgreSQL enum type on your model, just like you would with tables, sequences or other databases objects: + +```c# +protected override void OnModelCreating(ModelBuilder builder) + => builder.HasPostgresEnum(); ``` -## Mapping your enum +This causes the EF Core provider to create your enum type, `mood`, with two labels: `happy` and `sad`. This will cause the appropriate migration to be created. + +#### Mapping your enum Even if your database enum is created, Npgsql has to know about it, and especially about your CLR enum type that should be mapped to it: -### [NpgsqlDataSource](#tab/with-datasource) +##### [NpgsqlDataSource](#tab/with-datasource) Since version 7.0, NpgsqlDataSource is the recommended way to use Npgsql. When using NpgsqlDataSource, map your enum when building your data source: ```c# -// Call UseNodaTime() when building your data source: +// Call MapEnum() when building your data source: var dataSourceBuilder = new NpgsqlDataSourceBuilder(/* connection string */); dataSourceBuilder.MapEnum(); var dataSource = dataSourceBuilder.Build(); @@ -51,7 +71,7 @@ var dataSource = dataSourceBuilder.Build(); builder.Services.AddDbContext(options => options.UseNpgsql(dataSource)); ``` -### [Without NpgsqlDatasource](#tab/without-datasource) +##### [Without NpgsqlDatasource](#tab/without-datasource) Since version 7.0, NpgsqlDataSource is the recommended way to use Npgsql. However, if you're not yet using NpgsqlDataSource, map enums by adding the following code, *before* any EF Core operations take place. An appropriate place for this is in the static constructor on your DbContext class: @@ -60,18 +80,16 @@ static MyDbContext() => NpgsqlConnection.GlobalTypeMapper.MapEnum(); ``` +> [!NOTE] +> If you have multiple context types, all `MapEnum` invocations must be done before *any* of them is used; this means that the code cannot be in your static constructors, but must be moved to the program start. + *** This code lets Npgsql know that your CLR enum type, `Mood`, should be mapped to a database enum called `mood`. Note that if your enum is in a custom schema (not `public`), you must specify that schema in the call to `MapEnum`. -If you're curious as to inner workings, this code maps the enum with the ADO.NET provider - [see here for the full docs](http://www.npgsql.org/doc/types/enums_and_composites.html). When the Npgsql EF Core first initializes, it calls into the ADO.NET provider to get all mapped enums, and sets everything up internally at the EF Core layer as well. - -> [!NOTE] -> If you have multiple context types, all `MapEnum` invocations must be done before *any* of them is used; this means that the code cannot be in your static constructors, but must be moved to the program start. - ## Using enum properties -Once your enum is mapped and created in the database, you can use your CLR enum type just like any other property: +Once your enum is properly set up with EF, you can use your CLR enum type just like any other property: ```c# public class Blog @@ -96,13 +114,13 @@ using (var ctx = new MyDbContext()) The Npgsql provider only allow adding new values to existing enums, and the appropriate migrations will be automatically created as you add values to your CLR enum type. However, PostgreSQL itself doesn't support removing enum values (since these may be in use), and while renaming values is supported, it isn't automatically done by the provider to avoid using unreliable detection heuristics. Renaming an enum value can be done by including [raw SQL](https://docs.microsoft.com/en-us/ef/core/managing-schemas/migrations/managing?tabs=dotnet-core-cli#arbitrary-changes-via-raw-sql) in your migrations as follows: ```c# -migrationBuilder.Sql(@"ALTER TYPE mood RENAME VALUE 'happy' TO 'thrilled';"); +migrationBuilder.Sql("ALTER TYPE mood RENAME VALUE 'happy' TO 'thrilled';"); ``` As always, test your migrations carefully before running them on production databases. ## Scaffolding from an existing database -If you're creating your model from an existing database, the provider will recognize enums in your database, and scaffold the appropriate `HasPostgresEnum()` lines in your model. However, the scaffolding process has no knowledge of your CLR type, and will therefore skip your enum columns (warnings will be logged). You will have to create the CLR type, add the global mapping and add the properties to your entities. +If you're creating your model from an existing database, the provider will recognize enums in your database, and scaffold the appropriate `HasPostgresEnum()` lines in your model. However, the scaffolding process has no knowledge of your CLR type, and will therefore skip your enum columns (warnings will be logged). You will have to create the CLR type and perform the proper setup as described above. -In the future it may be possible to scaffold the actual enum type (and with it the properties), but this doesn't happen at the moment. +In the future it may be possible to scaffold the actual enum type (and with it the properties), but this isn't supported at the moment. diff --git a/docs/mapping/nodatime.md b/docs/mapping/nodatime.md index bb627438e3..db9a88ab35 100644 --- a/docs/mapping/nodatime.md +++ b/docs/mapping/nodatime.md @@ -12,36 +12,45 @@ Beyond NodaTime's general advantages, some specific advantages NodaTime for Post ## Setup -To set up the NodaTime plugin, add the [Npgsql.EntityFrameworkCore.PostgreSQL.NodaTime nuget](https://www.nuget.org/packages/Npgsql.EntityFrameworkCore.PostgreSQL.NodaTime) to your project. Then, configure NodaTime as follows: +To set up the NodaTime plugin, add the [Npgsql.EntityFrameworkCore.PostgreSQL.NodaTime nuget](https://www.nuget.org/packages/Npgsql.EntityFrameworkCore.PostgreSQL.NodaTime) to your project. Then, configure the NodaTime plugin as follows: -### [NpgsqlDataSource](#tab/with-datasource) +### [EF 9.0, with a connection string](#tab/ef9-with-connection-string) -Since version 7.0, NpgsqlDataSource is the recommended way to use Npgsql. When using NpsgqlDataSource, NodaTime currently has to be configured twice - once at the EF level, and once at the underlying ADO.NET level (there are plans to improve this): +If you're passing a connection string to `UseNpgsql`, simply add the `UseNodaTime` call as follows: ```c# -// Call UseNodaTime() when building your data source: -var dataSourceBuilder = new NpgsqlDataSourceBuilder(/* connection string */); +builder.Services.AddDbContext(options => options.UseNpgsql( + "", + o => o.UseNodaTime())); +``` + +This configures all aspects of Npgsql to use the NodaTime plugin - both at the EF and the lower-level Npgsql layer. + +### [With an external NpgsqlDataSource](#tab/with-datasource) + +If you're creating an external NpgsqlDataSource and passing it to `UseNpgsql`, you must call `UseNodaTime` on your NpgsqlDataSourceBuilder independently of the EF-level setup: + +```c# +var dataSourceBuilder = new NpgsqlDataSourceBuilder(""); dataSourceBuilder.UseNodaTime(); var dataSource = dataSourceBuilder.Build(); -// Then, when configuring EF Core with UseNpgsql(), call UseNodaTime() there as well: -builder.Services.AddDbContext(options => - options.UseNpgsql(dataSource, o => o.UseNodaTime())); +builder.Services.AddDbContext(options => options.UseNpgsql( + dataSource, + o => o.UseNodaTime())); ``` -### [Without NpgsqlDatasource](#tab/without-datasource) - -Since version 7.0, NpgsqlDataSource is the recommended way to use Npgsql. However, if you're not yet using NpgsqlDataSource, configure NodaTime as follows: +### [Older EF versions, with a connection string](#tab/legacy-with-connection-string) ```c# -// Configure NodaTime at the ADO.NET level. +// Configure UseNodaTime at the ADO.NET level. // This code must be placed at the beginning of your application, before any other Npgsql API is called; an appropriate place for this is in the static constructor on your DbContext class: static MyDbContext() => NpgsqlConnection.GlobalTypeMapper.UseNodaTime(); // Then, when configuring EF Core with UseNpgsql(), call UseNodaTime(): builder.Services.AddDbContext(options => - options.UseNpgsql(/* connection string */, o => o.UseNodaTime())); + options.UseNpgsql("", o => o.UseNodaTime())); ``` *** diff --git a/docs/mapping/nts.md b/docs/mapping/nts.md index 4a08c52c7b..bf4f9e729a 100644 --- a/docs/mapping/nts.md +++ b/docs/mapping/nts.md @@ -9,26 +9,35 @@ Note that the EF Core NetTopologySuite plugin depends on [the Npgsql ADO.NET Net ## Setup -To use the NetTopologySuite plugin, add the [Npgsql.EntityFrameworkCore.PostgreSQL.NetTopologySuite nuget](https://www.nuget.org/packages/Npgsql.EntityFrameworkCore.PostgreSQL.NetTopologySuite) to your project. Then, configure NetTopologySuite as followed: +To use the NetTopologySuite plugin, add the [Npgsql.EntityFrameworkCore.PostgreSQL.NetTopologySuite nuget](https://www.nuget.org/packages/Npgsql.EntityFrameworkCore.PostgreSQL.NetTopologySuite) to your project. Then, configure the NetTopologySuite plugin as follows: -### [NpgsqlDataSource](#tab/with-datasource) +### [EF 9.0, with a connection string](#tab/ef9-with-connection-string) -Since version 7.0, NpgsqlDataSource is the recommended way to use Npgsql. When using NpsgqlDataSource, NetTopologySuite currently has to be configured twice - once at the EF level, and once at the underlying ADO.NET level (there are plans to improve this): +If you're passing a connection string to `UseNpgsql`, simply add the `UseNetTopologySuite` call as follows: ```c# -// Call UseNetTopologySuite() when building your data source: -var dataSourceBuilder = new NpgsqlDataSourceBuilder(/* connection string */); +builder.Services.AddDbContext(options => options.UseNpgsql( + "", + o => o.UseNetTopologySuite())); +``` + +This configures all aspects of Npgsql to use the NetTopologySuite plugin - both at the EF and the lower-level Npgsql layer. + +### [With an external NpgsqlDataSource](#tab/with-datasource) + +If you're creating an external NpgsqlDataSource and passing it to `UseNpgsql`, you must call `UseNetTopologySuite` on your NpgsqlDataSourceBuilder independently of the EF-level setup: + +```c# +var dataSourceBuilder = new NpgsqlDataSourceBuilder(""); dataSourceBuilder.UseNetTopologySuite(); var dataSource = dataSourceBuilder.Build(); -// Then, when configuring EF Core with UseNpgsql(), call UseNetTopologySuite() there as well: -builder.Services.AddDbContext(options => - options.UseNpgsql(dataSource, o => o.UseNetTopologySuite())); +builder.Services.AddDbContext(options => options.UseNpgsql( + dataSource, + o => o.UseNetTopologySuite())); ``` -### [Without NpgsqlDatasource](#tab/without-datasource) - -Since version 7.0, NpgsqlDataSource is the recommended way to use Npgsql. However, if you're not yet using NpgsqlDataSource, configure NetTopologySuite as follows: +### [Older EF versions, with a connection string](#tab/legacy-with-connection-string) ```c# // Configure NetTopologySuite at the ADO.NET level. @@ -38,12 +47,12 @@ static MyDbContext() // Then, when configuring EF Core with UseNpgsql(), call UseNetTopologySuite(): builder.Services.AddDbContext(options => - options.UseNpgsql(/* connection string */, o => o.UseNetTopologySuite())); + options.UseNpgsql("", o => o.UseNetTopologySuite())); ``` *** -The above sets up all the necessary EF mappings and operation translators. In addition, to make sure that the PostGIS extension is installed in your database, add the following to your DbContext: +The above sets up all the necessary EF mappings and operation translators. If you're using EF 6.0, you also need to make sure that the PostGIS extension is installed in your database (later versions do this automatically). Add the following to your DbContext: ```c# protected override void OnModelCreating(ModelBuilder builder) diff --git a/docs/release-notes/9.0.md b/docs/release-notes/9.0.md index 737e7f1400..af54957033 100644 --- a/docs/release-notes/9.0.md +++ b/docs/release-notes/9.0.md @@ -2,16 +2,52 @@ Npgsql.EntityFrameworkCore.PostgreSQL version 9.0 is under development; previews are available on [nuget.org](https://www.nuget.org/packages/Npgsql.EntityFrameworkCore.PostgreSQL). +## Improved configuration for enums and plugins + +Previously, configuration around enums and plugins (NodaTime, NetTopologySuite) was complicated, requiring multiple setup actions at both the EF and the lower-level Npgsql layers. EF 9.0 improves the configuration story, allowing you to configure enums and plugins via a single EF gesture: + +```c# +builder.Services.AddDbContext(options => options.UseNpgsql( + "", + o => o.MapEnum("mood"))); +``` + +This takes care of everything - EF configuration, lower-level Npgsql configuration and even the addition of the enum to the EF model, which ensures that the enum is created in the database in EF migrations. + +See the [enum](../mapping/enum.md), [NodaTime](../mapping/nodatime.md) and [NetTopologySuite](../mapping/nts.md) documentation for more details. + ## UUIDv7 GUIDs are generated by default When your entity types have a `Guid` key, EF Core by default generates key values for new entities client-side - in .NET - before inserting those entity types to the database; this can be better for performance in some situations. Before version 9.0, the provider generated random GUIDs (version 4) by calling the .NET [`Guid.NewGuid()`](https://learn.microsoft.com/en-us/dotnet/api/system.guid.newguid?view=net-8.0#system-guid-newguid) function. Unfortunately, random GUIDs aren't ideal for database indexing and can cause performance issues. -Version 9.0 of the provider now generates the recently standardized version 7 GUIDs, which is a sequential GUID type that's more appropriate for database indexes and improves their performance. This new behavior is by default and will take effect simply by upgrading the provider version. +Version 9.0 of the provider now generates the recently standardized version 7 GUIDs, which is a sequential GUID type that's more appropriate for database indexes and improves their performance. This new behavior is on by default and takes effect simply by upgrading the provider version. See [this post](https://www.cybertec-postgresql.com/en/unexpected-downsides-of-uuid-keys-in-postgresql) for more details and performance numbers on random vs. sequential GUIDs. Thanks to [@ChrisJollyAU](https://github.com/ChrisJollyAU) and [@Timovzl](https://github.com/Timovzl) for contributing this improvement! +## Breaking changes + +### Enum mappings must now be configured at the EF level + +Previously, enum configuration involved mapping the enum at the lower-level Npgsql layer (either via `NpgsqlDataSourceBuilder.MapEnum` or via `NpgsqlConnection.GlobalTypeMapper.MapEnum`); the EF provider automatically picked this configuration up for the EF-level setup. Unfortunately, this design created numerous issues and bugs. + +As part of the improved enum configuration story in version 9.0 ([see above](#improved-configuration-for-enums-and-plugins)), enums must now be configured at the EF level; although this is a breaking change for existing applications, it usually results in simplified setup code and fixes various bugs and problematic behavior. + +If your application calls `UseNpgsql` with a simple connection string (rather than an NpgsqlDataSource), it simply needs to add a `MapEnum` call there: + +```c# +builder.Services.AddDbContext(options => options.UseNpgsql( + "", + o => o.MapEnum("mood"))); +``` + +All other setup code - the `MapEnum` call on `NpgsqlConnection.GlobalTypeMapper` and the `HasPostgresEnum` call in `OnModelCreating` - can be removed. + +If your application passes an NpgsqlDataSource to `UseNpgsql`, it also needs to add the `MapEnum` call as above; but the `MapEnum` call on `NpgsqlDataSourceBuilder` must also be kept. + +See the [enum documentation](../mapping/enum.md) for more information. + ## Contributors A big thank you to all the following people who contributed to the 9.0 release! From 028b9439399fab881c082d3076d64171eb656b88 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Fri, 13 Sep 2024 19:39:10 +0200 Subject: [PATCH 163/207] Link to the 9.0 release notes --- docs/mapping/enum.md | 2 +- docs/release-notes/9.0.md | 3 +++ docs/toc.yml | 6 ++++-- 3 files changed, 8 insertions(+), 3 deletions(-) diff --git a/docs/mapping/enum.md b/docs/mapping/enum.md index f52f0d25da..ef610689da 100644 --- a/docs/mapping/enum.md +++ b/docs/mapping/enum.md @@ -23,7 +23,7 @@ builder.Services.AddDbContext(options => options.UseNpgsql( This configures all aspects of Npgsql to use your `Mood` enum - both at the EF and the lower-level Npgsql layer - and ensures that the enum is created in the database in EF migrations. -### [With an external NpgsqlDataSource](#tab/with-datasource) +### [With an external NpgsqlDataSource](#tab/with-external-datasource) If you're creating an external NpgsqlDataSource and passing it to `UseNpgsql`, you must make sure to map your enum on that data independently of the EF-level setup: diff --git a/docs/release-notes/9.0.md b/docs/release-notes/9.0.md index af54957033..4585ca8191 100644 --- a/docs/release-notes/9.0.md +++ b/docs/release-notes/9.0.md @@ -2,6 +2,9 @@ Npgsql.EntityFrameworkCore.PostgreSQL version 9.0 is under development; previews are available on [nuget.org](https://www.nuget.org/packages/Npgsql.EntityFrameworkCore.PostgreSQL). +> [!NOTE] +> The following release notes and breaking changes are partial. More will be added nearer to the 9.0 final release. + ## Improved configuration for enums and plugins Previously, configuration around enums and plugins (NodaTime, NetTopologySuite) was complicated, requiring multiple setup actions at both the EF and the lower-level Npgsql layers. EF 9.0 improves the configuration story, allowing you to configure enums and plugins via a single EF gesture: diff --git a/docs/toc.yml b/docs/toc.yml index c82ed27128..b4ed54fef4 100644 --- a/docs/toc.yml +++ b/docs/toc.yml @@ -2,14 +2,16 @@ href: index.md - name: Release notes items: + - name: "9.0 (prerelease)" + href: release-notes/9.0.md - name: "8.0" href: release-notes/8.0.md - - name: "7.0" - href: release-notes/7.0.md - name: "6.0" href: release-notes/6.0.md - name: Out of support items: + - name: "7.0" + href: release-notes/7.0.md - name: "5.0" href: release-notes/5.0.md - name: "3.1" From 27217c568f535980c3710046207311d4d85aee7b Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Tue, 17 Sep 2024 19:04:29 +0200 Subject: [PATCH 164/207] Document new EF/Npgsql configuration experience (#353) --- docs/index.md | 152 ++++++++++++++++++++++++++++---------- docs/release-notes/9.0.md | 32 +++++++- 2 files changed, 144 insertions(+), 40 deletions(-) diff --git a/docs/index.md b/docs/index.md index 61d481fc1e..c9699882b9 100644 --- a/docs/index.md +++ b/docs/index.md @@ -19,63 +19,139 @@ Below is a `.csproj` file for a console application that uses the Npgsql EF Core ```xml - netcoreapp3.0 + net8.0 - + ``` -## Defining a `DbContext` +## Defining a model and a `DbContext` + +Let's say you want to store blogs and their posts in their database; you can model these as .NET types as follows: ```c# -using System.Collections.Generic; -using Microsoft.EntityFrameworkCore; +public class Blog +{ + public int BlogId { get; set; } + public string Url { get; set; } + + public List Posts { get; set; } +} -namespace ConsoleApp.PostgreSQL +public class Post { - public class BloggingContext : DbContext - { - public DbSet Blogs { get; set; } - public DbSet 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 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; } - } + 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 +You then define a `DbContext` type which you'll use to interact with the database: + +### [OnConfiguring](#tab/onconfiguring) -Consult [this tutorial](https://docs.microsoft.com/en-us/aspnet/core/data/ef-rp/intro) for general information on how to make ASP.NET work with EF Core. For Npgsql specifically, simply place the following in your `ConfigureServices` method in `Startup.cs`: +Using `OnConfiguring()` to configure your context is the easiest way to get started, but is discouraged for most production applications: ```c# -public void ConfigureServices(IServiceCollection services) +public class BloggingContext : DbContext { - // Other DI initializations + public DbSet Blogs { get; set; } + public DbSet Posts { get; set; } - services.AddDbContext(options => - options.UseNpgsql(Configuration.GetConnectionString("BloggingContext"))); + protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) + => optionsBuilder.UseNpgsql(""); } + +// At the point where you need to perform a database operation: +using var context = new BloggingContext(); +// Use the context... +``` + +### [DbContext pooling](#tab/context-pooling) + +```c# +var dbContextFactory = new PooledDbContextFactory( + new DbContextOptionsBuilder() + .UseNpgsql("") + .Options); + +// At the point where you need to perform a database operation: +using var context = dbContextFactory.CreateDbContext(); +// Use the context... +``` + +### [ASP.NET / DI](#tab/aspnet) + +When using ASP.NET - or any application with dependency injection - the context instance will be injected into your code. Use the following to configure EF with your DI container: + +```c# +var builder = WebApplication.CreateBuilder(args); + +builder.Services.AddDbContextPool(opt => + opt.UseNpgsql(builder.Configuration.GetConnectionString("BloggingContext"))); + +public class BloggingContext(DbContextOptions options) : DbContext(options) +{ + public DbSet Blogs { get; set; } + public DbSet Posts { get; set; } +} +``` + +*** + +For more information on getting started with EF, consult the [EF getting started documentation](https://learn.microsoft.com/en-us/ef/core/get-started/overview/first-app?tabs=netcore-cli). + +## Additional Npgsql configuration + +The Npgsql EF provider is built on top of the lower-level Npgsql ADO.NET provider ([docs](https://www.npgsql.org/doc/index.html)); these two separate components support various options you may want to configure. + +If you're using EF 9.0 or above, the `UseNpgsql()` is a single point where you can configure everything related to Npgsql. For example: + +```c# +builder.Services.AddDbContextPool(opt => + opt.UseNpgsql( + builder.Configuration.GetConnectionString("BloggingContext"), + o => o + .SetPostgresVersion(13, 0) + .UseNodaTime() + .MapEnum("mood"))); +``` + +The above configures the EF provider to produce SQL for PostgreSQL version 13 (avoiding newer incompatible features), adds a plugin allowing use of NodaTime for date/time type mapping, and maps a .NET enum type. Note that the last two also require configuration at the lower-level ADO.NET layer, which the code above does for you automatically. + +If you need to configure something at the lower-level ADO.NET layer, use `ConfigureDataSource()` as follows: + +```c# +builder.Services.AddDbContextPool(opt => + opt.UseNpgsql( + builder.Configuration.GetConnectionString("BloggingContext"), + o => o.ConfigureDataSource(dataSourceBuilder => dataSourceBuilder.UseClientCertificate(certificate)))); +``` + +`ConfigureDataSource()` provides access to a lower-level [`NpgsqlDataSourceBuilder`](../doc/basic-usage.html#data-source) which you can use to configure all aspects of the Npgsql ADO.NET provider. + +> [!WARNING] +> The EF provider internally creates an NpgsqlDataSource and uses that; for most configuration (e.g. connection string), the provider knows to switch between NpgsqlDataSources automatically. +> However, it's not possible to detect configuration differences within the `ConfigureDataSource()`; as a result, avoid performing varying configuration inside `ConfigureDataSource()`, since you may +> get the wrong NpgsqlDataSource. If you find yourself needing to vary Npgsql ADO.NET configuration, create an external NpgsqlDataSource yourself with the desired configuration and pass that to +> `UseNpgsql()` as described below. + +### Using an external NpgsqlDataSource + +If you're using a version of EF prior to 9.0, the above configuration methods aren't available. You can still create an `NpgsqlDataSource` yourself, and then pass it EF's `UseNpgsql()`: + +```c# +var dataSourceBuilder = new NpgsqlDataSourceBuilder(builder.Configuration.GetConnectionString("BloggingContext")); +dataSourceBuilder.MapEnum(); +dataSourceBuilder.UseNodaTime(); +var dataSource = dataSourceBuilder.Build(); + +builder.Services.AddDbContextPool(opt => opt.UseNpgsql(dataSource)); ``` ## Using an Existing Database (Database-First) diff --git a/docs/release-notes/9.0.md b/docs/release-notes/9.0.md index 4585ca8191..3df0095da0 100644 --- a/docs/release-notes/9.0.md +++ b/docs/release-notes/9.0.md @@ -5,12 +5,40 @@ Npgsql.EntityFrameworkCore.PostgreSQL version 9.0 is under development; previews > [!NOTE] > The following release notes and breaking changes are partial. More will be added nearer to the 9.0 final release. -## Improved configuration for enums and plugins +## Improved, unified configuration experience + +The Npgsql EF provider is built on top of the lower-level Npgsql ADO.NET provider; the configuration interface between these two layers was less than ideal, and configuration been more difficult than it should have been. For version 9.0, the configuration experience has been considerably improved. + +Since version 7, the Npgsql ADO.NET provider has been moving to [NpgsqlDataSource](../../doc/basic-usage.html#data-source) as the preferred way of configuration connections and obtaining them. At the EF level, it has been possible to pass an NpgsqlDataSource instance to `UseNpgsql()`; but this required that the user separately configure a data source and manage it. In addition, features such as plugins and enums require support from both the EF and ADO.NET layers, forcing users to perform multiple setup actions at the different layers. + +With version 9, `UseNpgsql()` becomes a single point for configuration, for both the EF and ADO.NET levels. EF can now internally set up an NpgsqlDataSource, automatically applying all the necessary configuration to it, and also exposes an API to allow users to apply arbitrary configuration to it as well: + +```c# +builder.Services.AddDbContextPool(opt => + opt.UseNpgsql( + builder.Configuration.GetConnectionString("BloggingContext"), + o => o + .SetPostgresVersion(13, 0) + .UseNodaTime() + .MapEnum("mood") + .ConfigureDataSource(dataSourceBuilder => dataSourceBuilder.UseClientCertificate(certificate)))); +``` + +In the above code, the following configuration gestures are performed: + +1. `SetPostgresVersion()` is an EF-only option to produce SQL for PostgreSQL version 13 (avoiding newer incompatible features) +2. `UseNodaTime()`, adds a plugin allowing use of NodaTime for date/time type mapping. This also requires an ADO.NET NodaTime plugin which needed to be configured separately, but this is now done automatically. +3. `MapEnum()` maps a .NET enum type. Like `UseNodaTime()`, this also used to require a separate ADO.NET configuration gesture, but is now done automatically. As an added bonus, doing this now also adds the enum to the model, causing the enum to be created in the database via EF's migrations. +4. `ConfigureDataSource()` exposes an NpgsqlDataSourceBuilder, which you can use to configure arbitrary ADO.NET options. In this example, the certificate is defined for the TLS authentication process. + +For more information, see the [getting started docs](../index.html). + +### Improved configuration for enums and plugins Previously, configuration around enums and plugins (NodaTime, NetTopologySuite) was complicated, requiring multiple setup actions at both the EF and the lower-level Npgsql layers. EF 9.0 improves the configuration story, allowing you to configure enums and plugins via a single EF gesture: ```c# -builder.Services.AddDbContext(options => options.UseNpgsql( +builder.Services.AddPooledDbContext(options => options.UseNpgsql( "", o => o.MapEnum("mood"))); ``` From eb0443de2915c401a2be82adf5227b3f06d086a3 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Fri, 20 Sep 2024 15:59:55 +0200 Subject: [PATCH 165/207] Bump docfx to 2.77.0 and adjust config (#357) --- docs/index.md | 2 +- docs/release-notes/8.0.md | 6 +++--- docs/release-notes/9.0.md | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/docs/index.md b/docs/index.md index c9699882b9..475bf4b2a8 100644 --- a/docs/index.md +++ b/docs/index.md @@ -133,7 +133,7 @@ builder.Services.AddDbContextPool(opt => o => o.ConfigureDataSource(dataSourceBuilder => dataSourceBuilder.UseClientCertificate(certificate)))); ``` -`ConfigureDataSource()` provides access to a lower-level [`NpgsqlDataSourceBuilder`](../doc/basic-usage.html#data-source) which you can use to configure all aspects of the Npgsql ADO.NET provider. +`ConfigureDataSource()` provides access to a lower-level [`NpgsqlDataSourceBuilder`](../Npgsql/basic-usage.md#data-source) which you can use to configure all aspects of the Npgsql ADO.NET provider. > [!WARNING] > The EF provider internally creates an NpgsqlDataSource and uses that; for most configuration (e.g. connection string), the provider knows to switch between NpgsqlDataSources automatically. diff --git a/docs/release-notes/8.0.md b/docs/release-notes/8.0.md index 596457b3e9..56c55f966d 100644 --- a/docs/release-notes/8.0.md +++ b/docs/release-notes/8.0.md @@ -189,9 +189,9 @@ Because of the NativeAOT and trimming work done for Npgsql 8.0 ([release notes]( PostgreSQL type | Default .NET type ---------------------------------------- | -------------------------- -JSON POCO mapping, JsonNode and subtypes | -Unmapped enums, ranges, multiranges | -Read PostgreSQL records as .NET tuples | +JSON POCO mapping, JsonNode and subtypes | +Unmapped enums, ranges, multiranges | +Read PostgreSQL records as .NET tuples | Existing code using the above features will start throwing exceptions after upgrading to version 8.0 of the EF Core provider; the exceptions provide explicit guidance on how to add the opt-ins. diff --git a/docs/release-notes/9.0.md b/docs/release-notes/9.0.md index 3df0095da0..09076c1ee6 100644 --- a/docs/release-notes/9.0.md +++ b/docs/release-notes/9.0.md @@ -9,7 +9,7 @@ Npgsql.EntityFrameworkCore.PostgreSQL version 9.0 is under development; previews The Npgsql EF provider is built on top of the lower-level Npgsql ADO.NET provider; the configuration interface between these two layers was less than ideal, and configuration been more difficult than it should have been. For version 9.0, the configuration experience has been considerably improved. -Since version 7, the Npgsql ADO.NET provider has been moving to [NpgsqlDataSource](../../doc/basic-usage.html#data-source) as the preferred way of configuration connections and obtaining them. At the EF level, it has been possible to pass an NpgsqlDataSource instance to `UseNpgsql()`; but this required that the user separately configure a data source and manage it. In addition, features such as plugins and enums require support from both the EF and ADO.NET layers, forcing users to perform multiple setup actions at the different layers. +Since version 7, the Npgsql ADO.NET provider has been moving to [NpgsqlDataSource](../../Npgsql/basic-usage.md#data-source) as the preferred way of configuration connections and obtaining them. At the EF level, it has been possible to pass an NpgsqlDataSource instance to `UseNpgsql()`; but this required that the user separately configure a data source and manage it. In addition, features such as plugins and enums require support from both the EF and ADO.NET layers, forcing users to perform multiple setup actions at the different layers. With version 9, `UseNpgsql()` becomes a single point for configuration, for both the EF and ADO.NET levels. EF can now internally set up an NpgsqlDataSource, automatically applying all the necessary configuration to it, and also exposes an API to allow users to apply arbitrary configuration to it as well: @@ -31,7 +31,7 @@ In the above code, the following configuration gestures are performed: 3. `MapEnum()` maps a .NET enum type. Like `UseNodaTime()`, this also used to require a separate ADO.NET configuration gesture, but is now done automatically. As an added bonus, doing this now also adds the enum to the model, causing the enum to be created in the database via EF's migrations. 4. `ConfigureDataSource()` exposes an NpgsqlDataSourceBuilder, which you can use to configure arbitrary ADO.NET options. In this example, the certificate is defined for the TLS authentication process. -For more information, see the [getting started docs](../index.html). +For more information, see the [getting started docs](../index.md). ### Improved configuration for enums and plugins From e0ca9255d89a3c7256fb6ab30ad0e55455798c24 Mon Sep 17 00:00:00 2001 From: Nikita Kazmin Date: Fri, 20 Sep 2024 18:03:27 +0300 Subject: [PATCH 166/207] Replace c# code with csharp (#360) --- docs/index.md | 14 ++++++------ docs/mapping/array.md | 2 +- docs/mapping/enum.md | 14 ++++++------ docs/mapping/full-text-search.md | 18 +++++++-------- docs/mapping/general.md | 6 ++--- docs/mapping/json.md | 20 ++++++++-------- docs/mapping/nodatime.md | 10 ++++---- docs/mapping/nts.md | 16 ++++++------- docs/mapping/range.md | 10 ++++---- docs/mapping/translations.md | 4 ++-- docs/misc/collations-and-case-sensitivity.md | 16 ++++++------- docs/misc/database-creation.md | 6 ++--- docs/misc/other.md | 8 +++---- docs/modeling/concurrency.md | 6 ++--- docs/modeling/generated-properties.md | 24 ++++++++++---------- docs/modeling/indexes.md | 12 +++++----- docs/modeling/tables.md | 4 ++-- docs/release-notes/2.1.md | 2 +- docs/release-notes/2.2.md | 4 ++-- docs/release-notes/3.1.md | 4 ++-- docs/release-notes/5.0.md | 2 +- docs/release-notes/6.0.md | 16 ++++++------- docs/release-notes/7.0.md | 4 ++-- docs/release-notes/8.0.md | 18 +++++++-------- docs/release-notes/9.0.md | 6 ++--- 25 files changed, 123 insertions(+), 123 deletions(-) diff --git a/docs/index.md b/docs/index.md index 475bf4b2a8..b7709ba3ba 100644 --- a/docs/index.md +++ b/docs/index.md @@ -31,7 +31,7 @@ Below is a `.csproj` file for a console application that uses the Npgsql EF Core Let's say you want to store blogs and their posts in their database; you can model these as .NET types as follows: -```c# +```csharp public class Blog { public int BlogId { get; set; } @@ -57,7 +57,7 @@ You then define a `DbContext` type which you'll use to interact with the databas Using `OnConfiguring()` to configure your context is the easiest way to get started, but is discouraged for most production applications: -```c# +```csharp public class BloggingContext : DbContext { public DbSet Blogs { get; set; } @@ -74,7 +74,7 @@ using var context = new BloggingContext(); ### [DbContext pooling](#tab/context-pooling) -```c# +```csharp var dbContextFactory = new PooledDbContextFactory( new DbContextOptionsBuilder() .UseNpgsql("") @@ -89,7 +89,7 @@ using var context = dbContextFactory.CreateDbContext(); When using ASP.NET - or any application with dependency injection - the context instance will be injected into your code. Use the following to configure EF with your DI container: -```c# +```csharp var builder = WebApplication.CreateBuilder(args); builder.Services.AddDbContextPool(opt => @@ -112,7 +112,7 @@ The Npgsql EF provider is built on top of the lower-level Npgsql ADO.NET provide If you're using EF 9.0 or above, the `UseNpgsql()` is a single point where you can configure everything related to Npgsql. For example: -```c# +```csharp builder.Services.AddDbContextPool(opt => opt.UseNpgsql( builder.Configuration.GetConnectionString("BloggingContext"), @@ -126,7 +126,7 @@ The above configures the EF provider to produce SQL for PostgreSQL version 13 (a If you need to configure something at the lower-level ADO.NET layer, use `ConfigureDataSource()` as follows: -```c# +```csharp builder.Services.AddDbContextPool(opt => opt.UseNpgsql( builder.Configuration.GetConnectionString("BloggingContext"), @@ -145,7 +145,7 @@ builder.Services.AddDbContextPool(opt => If you're using a version of EF prior to 9.0, the above configuration methods aren't available. You can still create an `NpgsqlDataSource` yourself, and then pass it EF's `UseNpgsql()`: -```c# +```csharp var dataSourceBuilder = new NpgsqlDataSourceBuilder(builder.Configuration.GetConnectionString("BloggingContext")); dataSourceBuilder.MapEnum(); dataSourceBuilder.UseNodaTime(); diff --git a/docs/mapping/array.md b/docs/mapping/array.md index 700c5c3dc7..09cecd5c19 100644 --- a/docs/mapping/array.md +++ b/docs/mapping/array.md @@ -9,7 +9,7 @@ PostgreSQL has the unique feature of supporting [*array data types*](https://www Simply define a regular .NET array or `List<>` property: -```c# +```csharp public class Post { public int Id { get; set; } diff --git a/docs/mapping/enum.md b/docs/mapping/enum.md index ef610689da..301e77dfb9 100644 --- a/docs/mapping/enum.md +++ b/docs/mapping/enum.md @@ -15,7 +15,7 @@ If you're using EF 9.0 or above, simply call `MapEnum` inside your `UseNpgsql` i If you're passing a connection string to `UseNpgsql`, simply add the `MapEnum` call as follows: -```c# +```csharp builder.Services.AddDbContext(options => options.UseNpgsql( "", o => o.MapEnum("mood"))); @@ -27,7 +27,7 @@ This configures all aspects of Npgsql to use your `Mood` enum - both at the EF a If you're creating an external NpgsqlDataSource and passing it to `UseNpgsql`, you must make sure to map your enum on that data independently of the EF-level setup: -```c# +```csharp var dataSourceBuilder = new NpgsqlDataSourceBuilder(""); dataSourceBuilder.MapEnum(); var dataSource = dataSourceBuilder.Build(); @@ -47,7 +47,7 @@ On versions of EF prior to 9.0, enum setup is more involved and consists of seve First, you must specify the PostgreSQL enum type on your model, just like you would with tables, sequences or other databases objects: -```c# +```csharp protected override void OnModelCreating(ModelBuilder builder) => builder.HasPostgresEnum(); ``` @@ -62,7 +62,7 @@ Even if your database enum is created, Npgsql has to know about it, and especial Since version 7.0, NpgsqlDataSource is the recommended way to use Npgsql. When using NpgsqlDataSource, map your enum when building your data source: -```c# +```csharp // Call MapEnum() when building your data source: var dataSourceBuilder = new NpgsqlDataSourceBuilder(/* connection string */); dataSourceBuilder.MapEnum(); @@ -75,7 +75,7 @@ builder.Services.AddDbContext(options => options.UseNpgsql(dataSource Since version 7.0, NpgsqlDataSource is the recommended way to use Npgsql. However, if you're not yet using NpgsqlDataSource, map enums by adding the following code, *before* any EF Core operations take place. An appropriate place for this is in the static constructor on your DbContext class: -```c# +```csharp static MyDbContext() => NpgsqlConnection.GlobalTypeMapper.MapEnum(); ``` @@ -91,7 +91,7 @@ This code lets Npgsql know that your CLR enum type, `Mood`, should be mapped to Once your enum is properly set up with EF, you can use your CLR enum type just like any other property: -```c# +```csharp public class Blog { public int Id { get; set; } @@ -113,7 +113,7 @@ using (var ctx = new MyDbContext()) The Npgsql provider only allow adding new values to existing enums, and the appropriate migrations will be automatically created as you add values to your CLR enum type. However, PostgreSQL itself doesn't support removing enum values (since these may be in use), and while renaming values is supported, it isn't automatically done by the provider to avoid using unreliable detection heuristics. Renaming an enum value can be done by including [raw SQL](https://docs.microsoft.com/en-us/ef/core/managing-schemas/migrations/managing?tabs=dotnet-core-cli#arbitrary-changes-via-raw-sql) in your migrations as follows: -```c# +```csharp migrationBuilder.Sql("ALTER TYPE mood RENAME VALUE 'happy' TO 'thrilled';"); ``` diff --git a/docs/mapping/full-text-search.md b/docs/mapping/full-text-search.md index d740b57210..090bc70006 100644 --- a/docs/mapping/full-text-search.md +++ b/docs/mapping/full-text-search.md @@ -6,7 +6,7 @@ PostgreSQL has [built-in support for full-text search](https://www.postgresql.or PostgreSQL full text search types are mapped onto .NET types built-in to Npgsql. The `tsvector` type is mapped to `NpgsqlTsVector` and `tsquery` is mapped to `NpgsqlTsQuery`. This means you can use properties of type `NpgsqlTsVector` directly in your model to create `tsvector` columns. The `NpgsqlTsQuery` type on the other hand, is used in LINQ queries. -```c# +```csharp public class Product { public int Id { get; set; } @@ -24,7 +24,7 @@ public class Product This method adds a `tsvector` column to your table, that is automatically updated when the row is modified. First, add an `NpgsqlTsVector` property to your entity: -```c# +```csharp public class Product { public int Id { get; set; } @@ -43,7 +43,7 @@ Setting up the column to be auto-updated depends on your PostgreSQL version. On The following will set up a generated `tsvector` column, over which you can easily create an index: -```c# +```csharp protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity() @@ -60,7 +60,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) First, modify the `OnModelCreating()` of your context class to add an index as follows: -```c# +```csharp protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity() @@ -71,7 +71,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) Now generate a migration (`dotnet ef migrations add ....`), and open it with your favorite editor, adding the following: -```c# +```csharp public partial class CreateProductTable : Migration { protected override void Up(MigrationBuilder migrationBuilder) @@ -99,7 +99,7 @@ public partial class CreateProductTable : Migration Once your auto-updated `tsvector` column is set up, any inserts or updates on the `Products` table will now update the `SearchVector` column and maintain it automatically. You can query it as follows: -```c# +```csharp var context = new ProductDbContext(); var npgsql = context.Products .Where(p => p.SearchVector.Matches("Npgsql")) @@ -112,7 +112,7 @@ Version 5.0.0 of the provider includes sugar for defining the appropriate expres #### [Version 5.0.0](#tab/v5) -```c# +```csharp modelBuilder.Entity() .HasIndex(b => new { b.Title, b.Description }) .HasMethod("GIN") @@ -123,7 +123,7 @@ modelBuilder.Entity() Create a migration which will contain the index creation SQL (`dotnet ef migrations add ...`). At this point, open the generated migration with your editor and add the following: -```c# +```csharp protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.Sql(@"CREATE INDEX fts_idx ON ""Product"" USING GIN (to_tsvector('english', ""Name"" || ' ' || ""Description""));"); @@ -138,7 +138,7 @@ protected override void Down(MigrationBuilder migrationBuilder) Once the index is created on the `Title` and `Description` columns, you can query as follows: -```c# +```csharp var context = new ProductDbContext(); var npgsql = context.Products .Where(p => EF.Functions.ToTsVector("english", p.Title + " " + p.Description) diff --git a/docs/mapping/general.md b/docs/mapping/general.md index 706714e24a..7734fe3982 100644 --- a/docs/mapping/general.md +++ b/docs/mapping/general.md @@ -4,7 +4,7 @@ The EF Core provider transparently maps the types supported by Npgsql at the ADO This means that you can use PostgreSQL-specific types, such as `inet` or `circle`, directly in your entities. Simply define your properties just as if they were a simple type, such as a `string`: -```c# +```csharp public class MyEntity { public int Id { get; set; } @@ -25,14 +25,14 @@ In some cases, your .NET property type can be mapped to several PostgreSQL data ## [Data Annotations](#tab/data-annotations) -```c# +```csharp [Column(TypeName="jsonb")] public string SomeStringProperty { get; set; } ``` ## [Fluent API](#tab/fluent-api) -```c# +```csharp builder.Entity() .Property(b => b.SomeStringProperty) .HasColumnType("jsonb"); diff --git a/docs/mapping/json.md b/docs/mapping/json.md index 465e170b4d..78db86bca7 100644 --- a/docs/mapping/json.md +++ b/docs/mapping/json.md @@ -18,7 +18,7 @@ The simplest form of mapping to JSON is via a regular string property, just like ### [Data Annotations](#tab/data-annotations) -```c# +```csharp public class SomeEntity { public int Id { get; set; } @@ -29,7 +29,7 @@ public class SomeEntity ### [Fluent API](#tab/fluent-api) -```c# +```csharp class MyContext : DbContext { public DbSet SomeEntities { get; set; } @@ -67,7 +67,7 @@ Npgsql's support for `ToJson()` is fully aligned with the general EF support; se To get you started quickly, assume that we have the following Customer type, with a Details property that we want to map to a single JSON column in the database: -```c# +```csharp public class Customer { public int Id { get; set; } @@ -90,7 +90,7 @@ public class Order // Part of the JSON column To instruct EF to map CustomerDetails - and within it, Order - to a JSON column, configure it as follows: -```c# +```csharp protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity() @@ -112,7 +112,7 @@ To use traditional POCO mapping, configure a property a mapping to map to a `jso ### [Data Annotations](#tab/data-annotations) -```c# +```csharp public class Customer { public int Id { get; set; } @@ -136,7 +136,7 @@ public class Order // Part of the JSON column ### [Fluent API](#tab/fluent-api) -```c# +```csharp class MyContext : DbContext { public DbSet SomeEntities { get; set; } @@ -178,7 +178,7 @@ Note that when using this mapping, only limited forms of LINQ querying is suppor If your column JSON schema isn't stable, a strongly-typed POCO mapping may not be appropriate. The Npgsql provider also allows you to map the DOM document type provided by [System.Text.Json APIs](https://devblogs.microsoft.com/dotnet/try-the-new-system-text-json-apis/). -```c# +```csharp public class SomeEntity : IDisposable { public int Id { get; set; } @@ -192,7 +192,7 @@ Note that neither a data annotation nor the fluent API are required, as [JsonDoc Once a document is loaded from the database, you can traverse it: -```c# +```csharp var someEntity = context.Entities.First(); Console.WriteLine(someEntity.Customer.RootElement.GetProperty("Orders")[0].GetProperty("Price").GetInt32()); ``` @@ -208,7 +208,7 @@ Saving and loading documents these documents wouldn't be much use without the ab ### [Classic POCO Mapping](#tab/poco) -```c# +```csharp var joes = context.CustomerEntries .Where(e => e.Customer.Name == "Joe") .ToList(); @@ -216,7 +216,7 @@ var joes = context.CustomerEntries ### [JsonDocument Mapping](#tab/jsondocument) -```c# +```csharp var joes = context.CustomerEntries .Where(e => e.Customer.RootElement.GetProperty("Name").GetString() == "Joe") .ToList(); diff --git a/docs/mapping/nodatime.md b/docs/mapping/nodatime.md index db9a88ab35..f39df92171 100644 --- a/docs/mapping/nodatime.md +++ b/docs/mapping/nodatime.md @@ -18,7 +18,7 @@ To set up the NodaTime plugin, add the [Npgsql.EntityFrameworkCore.PostgreSQL.No If you're passing a connection string to `UseNpgsql`, simply add the `UseNodaTime` call as follows: -```c# +```csharp builder.Services.AddDbContext(options => options.UseNpgsql( "", o => o.UseNodaTime())); @@ -30,7 +30,7 @@ This configures all aspects of Npgsql to use the NodaTime plugin - both at the E If you're creating an external NpgsqlDataSource and passing it to `UseNpgsql`, you must call `UseNodaTime` on your NpgsqlDataSourceBuilder independently of the EF-level setup: -```c# +```csharp var dataSourceBuilder = new NpgsqlDataSourceBuilder(""); dataSourceBuilder.UseNodaTime(); var dataSource = dataSourceBuilder.Build(); @@ -42,7 +42,7 @@ builder.Services.AddDbContext(options => options.UseNpgsql( ### [Older EF versions, with a connection string](#tab/legacy-with-connection-string) -```c# +```csharp // Configure UseNodaTime at the ADO.NET level. // This code must be placed at the beginning of your application, before any other Npgsql API is called; an appropriate place for this is in the static constructor on your DbContext class: static MyDbContext() @@ -57,7 +57,7 @@ builder.Services.AddDbContext(options => The above sets up all the necessary mappings and operation translators. You can now use NodaTime types as regular properties in your entities, and even perform some operations: -```c# +```csharp public class Post { public int Id { get; set; } @@ -72,7 +72,7 @@ var recentPosts = context.Posts.Where(p => p.CreationTime > someInstant); The provider knows how to translate many members and methods on mapped NodaTime types. For example, the following query will be translated to SQL and evaluated server-side: -```c# +```csharp // Get all events which occurred on a Monday var mondayEvents = context.Events.Where(p => p.SomeDate.DayOfWeek == DayOfWeek.Monday); diff --git a/docs/mapping/nts.md b/docs/mapping/nts.md index bf4f9e729a..893592eb2d 100644 --- a/docs/mapping/nts.md +++ b/docs/mapping/nts.md @@ -15,7 +15,7 @@ To use the NetTopologySuite plugin, add the [Npgsql.EntityFrameworkCore.PostgreS If you're passing a connection string to `UseNpgsql`, simply add the `UseNetTopologySuite` call as follows: -```c# +```csharp builder.Services.AddDbContext(options => options.UseNpgsql( "", o => o.UseNetTopologySuite())); @@ -27,7 +27,7 @@ This configures all aspects of Npgsql to use the NetTopologySuite plugin - both If you're creating an external NpgsqlDataSource and passing it to `UseNpgsql`, you must call `UseNetTopologySuite` on your NpgsqlDataSourceBuilder independently of the EF-level setup: -```c# +```csharp var dataSourceBuilder = new NpgsqlDataSourceBuilder(""); dataSourceBuilder.UseNetTopologySuite(); var dataSource = dataSourceBuilder.Build(); @@ -39,7 +39,7 @@ builder.Services.AddDbContext(options => options.UseNpgsql( ### [Older EF versions, with a connection string](#tab/legacy-with-connection-string) -```c# +```csharp // Configure NetTopologySuite at the ADO.NET level. // This code must be placed at the beginning of your application, before any other Npgsql API is called; an appropriate place for this is in the static constructor on your DbContext class: static MyDbContext() @@ -54,7 +54,7 @@ builder.Services.AddDbContext(options => The above sets up all the necessary EF mappings and operation translators. If you're using EF 6.0, you also need to make sure that the PostGIS extension is installed in your database (later versions do this automatically). Add the following to your DbContext: -```c# +```csharp protected override void OnModelCreating(ModelBuilder builder) { builder.HasPostgresExtension("postgis"); @@ -63,7 +63,7 @@ protected override void OnModelCreating(ModelBuilder builder) At this point spatial support is set up. You can now use NetTopologySuite types as regular properties in your entities, and even perform some operations: -```c# +```csharp public class City { public int Id { get; set; } @@ -78,7 +78,7 @@ var nearbyCities = context.Cities.Where(c => c.Location.Distance(somePoint) < 10 With the code above, the provider will create a database column of type `geometry`. This is perfectly fine, but be aware that this type accepts any geometry type (point, polygon...), with any coordinate system (XY, XYZ...). It's good practice to constrain the column to the exact type of data you will be storing, but unfortunately the provider isn't aware of your required coordinate system and therefore can't do that for you. Consider explicitly specifying your column types on your properties as follows: -```c# +```csharp [Column(TypeName="geometry (point)")] public Point Location { get; set; } ``` @@ -91,7 +91,7 @@ PostGIS has two types: `geometry` (for Cartesian coordinates) and `geography` (f The Npgsql provider will be default map all NetTopologySuite types to PostGIS `geometry`. However, you can instruct it to map certain properties to `geography` instead: -```c# +```csharp protected override void OnModelCreating(ModelBuilder builder) { builder.Entity().Property(b => b.Location).HasColumnType("geography (point)"); @@ -100,7 +100,7 @@ protected override void OnModelCreating(ModelBuilder builder) or via an attribute: -```c# +```csharp public class City { public int Id { get; set; } diff --git a/docs/mapping/range.md b/docs/mapping/range.md index 390820f5e7..0255d08921 100644 --- a/docs/mapping/range.md +++ b/docs/mapping/range.md @@ -8,7 +8,7 @@ In addition, PostgreSQL 14 introduced *multiranges*, which are basically sorted Npgsql maps PostgreSQL ranges to the generic CLR type `NpgsqlRange`: -```c# +```csharp public class Event { public int Id { get; set; } @@ -25,7 +25,7 @@ PostgreSQL comes with 6 built-in ranges: `int4range`, `int8range`, `numrange`, ` To make the EF Core type mapper aware of your user-defined range, call the `MapRange()` method in your context's `OnConfiguring()` method as follows: -```c# +```csharp protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) => optionsBuilder.UseNpgsql( "", @@ -36,7 +36,7 @@ This allows you to have properties of type `NpgsqlRange`, which will be m The above does *not* create the `floatrange` type for you. In order to do that, include the following in your context's `OnModelCreating()`: -```c# +```csharp protected override void OnModelCreating(ModelBuilder modelBuilder) => modelBuilder.HasPostgresRange("floatrange", "real"); ``` @@ -50,7 +50,7 @@ This will cause the appropriate [`CREATE TYPE ... AS RANGE`](https://www.postgre Npgsql maps arrays or lists of `NpgsqlRange` to PostgreSQL multiranges: -```c# +```csharp public class Store { public int Id { get; set; } @@ -63,7 +63,7 @@ public class Store Ranges can be queried via extensions methods on `NpgsqlRange`: -```c# +```csharp var events = context.Events.Where(p => p.Duration.Contains(someDate)); ``` diff --git a/docs/mapping/translations.md b/docs/mapping/translations.md index 9e8f851454..b5cfcf6469 100644 --- a/docs/mapping/translations.md +++ b/docs/mapping/translations.md @@ -306,7 +306,7 @@ The PostgreSQL aggregate functions are documented [here](https://www.postgresql. Aggregate functions can be used as follows: -```c# +```csharp var query = ctx.Set() .GroupBy(c => c.City) .Select( @@ -319,7 +319,7 @@ var query = ctx.Set() To use functions accepting a tuple_of_2, project out from the group as follows: -```c# +```csharp var query = ctx.Set() .GroupBy(c => c.City) .Select( diff --git a/docs/misc/collations-and-case-sensitivity.md b/docs/misc/collations-and-case-sensitivity.md index 48ce06299a..d2cafdd08f 100644 --- a/docs/misc/collations-and-case-sensitivity.md +++ b/docs/misc/collations-and-case-sensitivity.md @@ -18,7 +18,7 @@ While PostgreSQL has supported collations for a long time, supported was limited In PostgreSQL, collations are first-class, named database objects which can be created and dropped, just like tables. To create a collation, place the following in your context's `OnModelCreating`: -```c# +```csharp modelBuilder.HasCollation("my_collation", locale: "en-u-ks-primary", provider: "icu", deterministic: false); ``` @@ -28,7 +28,7 @@ This creates a collation with the name `my_collation`: this is an arbitrary name Once a collation has been created in your database, you can specify it on columns: -```c# +```csharp protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.HasCollation("my_collation", locale: "en-u-ks-primary", provider: "icu", deterministic: false); @@ -44,7 +44,7 @@ This will cause all textual operators on this column to be case-insensitive. PostgreSQL also allows you to specify collations at the database level, when it is created: -```c# +```csharp protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.UseCollation(""); @@ -53,7 +53,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) Unfortunately, the database collation is quite limited in PostgreSQL; it notably does not support non-deterministic collations (e.g. case-insensitive ones). To work around this limitation, you can use EF Core's [pre-convention model configuration](https://docs.microsoft.com/ef/core/modeling/bulk-configuration#pre-convention-configuration) feature: -```c# +```csharp protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder) { configurationBuilder.Properties().UseCollation("my_collation"); @@ -68,7 +68,7 @@ The older PostgreSQL method for performing case-insensitive text operations is t `citext` is available in a PostgreSQL-bundled extension, so you'll first have to install it: -```c# +```csharp modelBuilder.HasPostgresExtension("citext"); ``` @@ -76,7 +76,7 @@ Specifying that a column should use `citext` is simply a matter of setting the c ### [Data Annotations](#tab/data-annotations) -```c# +```csharp public class Blog { public int Id { get; set; } @@ -87,7 +87,7 @@ public class Blog ### [Fluent API](#tab/fluent-api) -```c# +```csharp protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity().Property(b => b.Name) @@ -107,7 +107,7 @@ Some limitations (others are listed in [the PostgreSQL docs](https://www.postgre `ILIKE` is a PostgreSQL-specific operator that works just like `LIKE`, but is case-insensitive. If you only need to perform case-insensitive `LIKE` pattern matching, then this could be sufficient. The provider exposes this via `EF.Functions.ILike`: -```c# +```csharp var results = ctx.Blogs .Where(b => EF.Functions.ILike(b.Name, "a%b")) .ToList(); diff --git a/docs/misc/database-creation.md b/docs/misc/database-creation.md index 08ec5eb690..8e5f9a6a8a 100644 --- a/docs/misc/database-creation.md +++ b/docs/misc/database-creation.md @@ -6,7 +6,7 @@ When the Npgsql EF Core provider creates or deletes a database (`EnsureCreated() However, there are some PostgreSQL-like databases where the `postgres` database is not available. For these cases you can specify the administrative database as follows: -```c# +```csharp protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) => optionsBuilder.UseNpgsql( "", @@ -19,7 +19,7 @@ When creating a new database, [PostgreSQL allows specifying another "template database"](http://www.postgresql.org/docs/current/static/manage-ag-templatedbs.html) which will be copied as the basis for the new one. This can be useful for including database entities which are not managed by Entity Framework Core. You can trigger this by using `HasDatabaseTemplate` in your context's `OnModelCreating`: -```c# +```csharp protected override void OnModelCreating(ModelBuilder modelBuilder) => modelBuilder.UseDatabaseTemplate("my_template_db"); ``` @@ -28,7 +28,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) PostgreSQL allows you to locate your database in different parts of your filesystem, [via tablespaces](https://www.postgresql.org/docs/current/static/manage-ag-tablespaces.html). The Npgsql EF Core provider allows you to specify your database's namespace: -```c# +```csharp protected override void OnModelCreating(ModelBuilder modelBuilder) => modelBuilder.UseTablespace("my_tablespace"); ``` diff --git a/docs/misc/other.md b/docs/misc/other.md index 23ea4e7ef9..e51fcb8dbe 100644 --- a/docs/misc/other.md +++ b/docs/misc/other.md @@ -5,7 +5,7 @@ The Npgsql EF Core provider allows you to specify PostgreSQL extensions that should be set up in your database. Simply use `HasPostgresExtension` in your context's `OnModelCreating` method: -```c# +```csharp protected override void OnModelCreating(ModelBuilder modelBuilder) => modelBuilder.HasPostgresExtension("hstore"); ``` @@ -14,7 +14,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) The Npgsql EF Core provider provides a retrying execution strategy, which will attempt to detect most transient PostgreSQL/network errors and will automatically retry your operation. To enable, place the following code in your context's `OnModelConfiguring`: -```c# +```csharp protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) => optionsBuilder.UseNpgsql( "", @@ -29,7 +29,7 @@ The Npgsql allows you to provide a callback for verifying the server-provided ce The Npgsql EF Core provider allows you to set these two callbacks on the `DbContextOptionsBuilder` as follows: -```c# +```csharp protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) => optionsBuilder.UseNpgsql( "", @@ -49,7 +49,7 @@ You may also consider passing `Trust Server Certificate=true` in your connection If you're using CockroachDB, the Npgsql EF Core provider exposes its ["interleave in parent" feature](https://www.cockroachlabs.com/docs/stable/interleave-in-parent.html). Use the following code: -```c# +```csharp protected override void OnModelCreating(ModelBuilder modelBuilder) => modelBuilder.Entity() .UseCockroachDbInterleaveInParent( diff --git a/docs/modeling/concurrency.md b/docs/modeling/concurrency.md index 62ed2163e6..fc5a7e8743 100644 --- a/docs/modeling/concurrency.md +++ b/docs/modeling/concurrency.md @@ -13,7 +13,7 @@ Starting with version 7.0, you can map a `uint` property to the PostgreSQL `xmin ### [Data Annotations](#tab/data-annotations) -```c# +```csharp public class SomeEntity { public int Id { get; set; } @@ -25,7 +25,7 @@ public class SomeEntity ### [Fluent API](#tab/fluent-api) -```c# +```csharp class MyContext : DbContext { public DbSet SomeEntities { get; set; } @@ -49,7 +49,7 @@ public class SomeEntity In older version of the provider, use the following instead: -```c# +```csharp protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity().UseXminAsConcurrencyToken(); diff --git a/docs/modeling/generated-properties.md b/docs/modeling/generated-properties.md index c359dc7a3c..e466e9724d 100644 --- a/docs/modeling/generated-properties.md +++ b/docs/modeling/generated-properties.md @@ -25,7 +25,7 @@ The default value generation strategy is "identity by default". In other words, You can easily control the value generation strategy for the entire model. For example, to opt out of the change to identity columns, simply place the following in your context's `OnModelCreating()`: -```c# +```csharp protected override void OnModelCreating(ModelBuilder modelBuilder) => modelBuilder.UseIdentityByDefaultColumns(); ``` @@ -34,7 +34,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) Regardless of the model default, you can define a value-generation strategy on a property-by-property basis: -```c# +```csharp protected override void OnModelCreating(ModelBuilder modelBuilder) => modelBuilder.Entity().Property(b => b.Id).UseIdentityAlwaysColumn(); ``` @@ -43,7 +43,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) Identity columns have a standard sequence, managed behind the scenes by PostgreSQL; you can customize the sequence options for these. For example, the following makes the column values start at 100: -```c# +```csharp protected override void OnModelCreating(ModelBuilder modelBuilder) => modelBuilder.Entity().Property(b => b.Id) .HasIdentityOptions(startValue: 100); @@ -57,7 +57,7 @@ It is not possible to specify sequence options for serial columns, but you can s While identity and serial columns set up a sequence for you behind the scenes, sometimes you may want to manage sequence creation yourself. For example, you may want to have multiple columns drawing their default values from a single sequence. Adding a sequence to your model is described in [the general EF Core documentation](https://docs.microsoft.com/ef/core/modeling/relational/sequences); once the sequence is specified, you can simply set a column's default value to extract the next value from that sequence. Note that the SQL used to fetch the next value from a sequence differs across databases (see [the PostgreSQL docs](https://www.postgresql.org/docs/current/static/functions-sequence.html)). Your models' `OnModelCreating` should look like this: -```c# +```csharp protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.HasSequence("OrderNumbers") @@ -76,7 +76,7 @@ One disadvantage of database-generated values is that these values must be read To use HiLo, specify `UseHiLo` on a property in your model's `OnModelCreating`: -```c# +```csharp protected override void OnModelCreating(ModelBuilder modelBuilder) => modelBuilder.Entity() .Property(b => b.Id) @@ -85,7 +85,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) You can also make your model use HiLo everywhere: -```c# +```csharp protected override void OnModelCreating(ModelBuilder modelBuilder) => modelBuilder.UseHiLo(); ``` @@ -96,7 +96,7 @@ By default, for GUID key properties, a GUID is generated client-side by the EF p To have the provider generate GUIDs client-side for **non-key** properties, configure them as follows: -```c# +```csharp protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder @@ -110,7 +110,7 @@ If you prefer to generate values in the database instead, you can do so by speci ### [PG 13+](#tab/13) -```c# +```csharp protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder @@ -124,7 +124,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) Versions of PostgreSQL prior to 13 don't include any GUID/UUID generation functions, but extensions such as `uuid-ossp` or `pgcrypto` exist to fill thie gap. This can be done by placing the following code in your model's `OnModelCreating`: -```c# +```csharp protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.HasPostgresExtension("uuid-ossp"); @@ -147,7 +147,7 @@ See [the PostgreSQL docs on UUID for more details](https://www.postgresql.org/do In many scenarios, it's useful to have a column containing the timestamp when the row was originally created. To do this, add a `DateTime` property to your entity type (or `Instant` if using NodaTime) , and configure its default with `HasDefaultValueSql` as follows: -```c# +```csharp protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder @@ -183,7 +183,7 @@ PostgreSQL 12 added support for [stored generated columns](https://www.postgresq ### [Version 5.0](#tab/efcore5) -```c# +```csharp protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity() @@ -194,7 +194,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) ### [Version 3.x](#tab/efcore3) -```c# +```csharp protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity() diff --git a/docs/modeling/indexes.md b/docs/modeling/indexes.md index b3e02ecbd9..464622a446 100644 --- a/docs/modeling/indexes.md +++ b/docs/modeling/indexes.md @@ -6,7 +6,7 @@ PostgreSQL and the Npgsql provider support the standard index modeling described PostgreSQL supports [covering indexes](https://paquier.xyz/postgresql-2/postgres-11-covering-indexes), which allow you to include "non-key" columns in your indexes. This allows you to perform index-only scans and can provide a significant performance boost: -```c# +```csharp protected override void OnModelCreating(ModelBuilder modelBuilder) => modelBuilder.Entity() .HasIndex(b => b.Id) @@ -26,7 +26,7 @@ CREATE INDEX "IX_Blog_Id" ON blogs ("Id") INCLUDE ("Name"); By default, when you create a unique index, PostgreSQL treats null values as distinct; this means that a unique index can contain multiple null values in a column. When creating an index, you can also instruct PostgreSQL that nulls should be treated as *non-distinct*; this causes a unique constraint violation to be raised if a column contains multiple null values: -```c# +```csharp protected override void OnModelCreating(ModelBuilder modelBuilder) => modelBuilder.Entity() .IsUnique() @@ -39,7 +39,7 @@ PostgreSQL supports a number of *index methods*, or *types*. These are specified The Npgsql EF Core provider allows you to specify the index method to be used by calling `HasMethod()` on your index in your context's `OnModelCreating` method: -```c# +```csharp protected override void OnModelCreating(ModelBuilder modelBuilder) => modelBuilder.Entity() .HasIndex(b => b.Url) @@ -50,7 +50,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) PostgreSQL allows you to specify [operator classes on your indexes](https://www.postgresql.org/docs/current/indexes-opclass.html), to allow tweaking how the index should work. Use the following code to specify an operator class: -```c# +```csharp protected override void OnConfiguring(DbContextOptionsBuilder builder) => modelBuilder.Entity() .HasIndex(b => new { b.Id, b.Name }) @@ -69,7 +69,7 @@ PostgreSQL allows configuring indexes with *storage parameters*, which can tweak To configure a storage parameter on an index, use the following code: -```c# +```csharp protected override void OnModelCreating(ModelBuilder modelBuilder) => modelBuilder.Entity() .HasIndex(b => b.Url) @@ -82,7 +82,7 @@ Creating an index can interfere with regular operation of a database. Normally P The EF provider allows you to specify that an index should be created *concurrently*, partially mitigating the above issues: -```c# +```csharp protected override void OnModelCreating(ModelBuilder modelBuilder) => modelBuilder.Entity() .HasIndex(b => b.Url) diff --git a/docs/modeling/tables.md b/docs/modeling/tables.md index 7a6f806d41..61084e0f0b 100644 --- a/docs/modeling/tables.md +++ b/docs/modeling/tables.md @@ -6,7 +6,7 @@ By default, EF Core will map to tables and columns named exactly after your .NET Starting with 3.0.0, you can use the [EFCore.NamingConventions](https://github.com/efcore/EFCore.NamingConventions) plugin to automatically set all your table and column names to snake_case instead: -```c# +```csharp protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) => optionsBuilder .UseNpgsql(...) @@ -39,7 +39,7 @@ PostgreSQL allows configuring tables with *storage parameters*, which can tweak To configure a storage parameter on a table, use the following code: -```c# +```csharp protected override void OnModelCreating(ModelBuilder modelBuilder) => modelBuilder.Entity().HasStorageParameter("fillfactor", 70); ``` diff --git a/docs/release-notes/2.1.md b/docs/release-notes/2.1.md index 031de9f09c..4362191ac7 100644 --- a/docs/release-notes/2.1.md +++ b/docs/release-notes/2.1.md @@ -14,7 +14,7 @@ Previous versions have allowed basic usage of PostGIS's spatial types via built- No more! Thanks to a new plugin infrastructure, the EF Core provider now has full-class support for PostGIS. You can now use the [NetTopologySuite](https://github.com/NetTopologySuite/NetTopologySuite) spatial library to map PostGIS types - NetTopologySuite's types are more complete, and best of all, the provider knows how to translate its operations to SQL. This allows you to write the following code: -```c# +```csharp var nearbyCities = context.Cities.Where(c => c.Location.Distance(somePoint) < 100); ``` diff --git a/docs/release-notes/2.2.md b/docs/release-notes/2.2.md index 770f09c37f..89de0f847b 100644 --- a/docs/release-notes/2.2.md +++ b/docs/release-notes/2.2.md @@ -12,7 +12,7 @@ Aside from general EF Core features new in 2.2.0, the Npgsql EF Core provider co PostgreSQL 11 introduced [covering indexes feature](https://paquier.xyz/postgresql-2/postgres-11-covering-indexes), which allow you to include "non-key" columns in your indexes. This allows you to perform index-only scans and can provide a significant performance boost. Support has been added in ([#697](https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL/issues/697)): -```c# +```csharp protected override void OnConfiguring(DbContextOptionsBuilder builder) => modelBuilder.Entity() .ForNpgsqlHasIndex(b => b.Id) @@ -27,7 +27,7 @@ Thanks to [@khellang](https://github.com/khellang) for contributing this! The provider already supported [PostgreSQL range types](https://www.postgresql.org/docs/current/rangetypes.html), but prior to 2.2 that support was limited to the built-in range types which come with PostgreSQL. [#329](https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL/issues/329) extends that support to range types which you define: -```c# +```csharp protected override void OnConfiguring(DbContextOptionsBuilder builder) => builder.UseNpgsql("...", b => b.MapRange("floatrange")); diff --git a/docs/release-notes/3.1.md b/docs/release-notes/3.1.md index 647aae5024..2c39309a3d 100644 --- a/docs/release-notes/3.1.md +++ b/docs/release-notes/3.1.md @@ -34,14 +34,14 @@ When producing a migration with 3.1, the Npgsql provider will attempt to automat If you wish to opt out of using IDENTITY columns and continue using SERIAL columns, set the following on your model: -```c# +```csharp protected override void OnModelCreating(ModelBuilder modelBuilder) => modelBuilder.UseSerialColumns(); ``` If you are using a PostgreSQL version older than 10, setting the compatibility mode is a better way to switch the default back to SERIAL columns: -```c# +```csharp protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) => optionsBuilder.UseNpgsql("...", o => o.SetPostgresVersion(9, 6)); ``` diff --git a/docs/release-notes/5.0.md b/docs/release-notes/5.0.md index 0a78c5cd3c..4e8bf9513a 100644 --- a/docs/release-notes/5.0.md +++ b/docs/release-notes/5.0.md @@ -37,7 +37,7 @@ Version 3.1 of the provider added support for [PostgreSQL generated columns](htt As a result, you must explicitly specify on all computed columns that they are stored: -```c# +```csharp modelBuilder.Entity() .Property(p => p.FullName) .HasComputedColumnSql("...", stored: true); diff --git a/docs/release-notes/6.0.md b/docs/release-notes/6.0.md index 908aa0f9ca..d2f457308f 100644 --- a/docs/release-notes/6.0.md +++ b/docs/release-notes/6.0.md @@ -103,7 +103,7 @@ When converting the `timestamp without time zone` column to `timestamp with time This means that your new `timestamptz` column now contains 10:00 UTC, which is probably not what you want: if the original values were in fact UTC values, you need them to be preserved as-is, changing only the column type. To do this, edit your migration and add the following to the top of your migration's Up and Down methods: -```c# +```csharp migrationBuilder.Sql("SET TimeZone='UTC';"); ``` @@ -119,7 +119,7 @@ This will ensure that no time zone conversions will be applied when converting t When switching from `timestamp without time zone` to `timezone with time zone`, you may have have non-UTC timestamp literals in your seeding configuration: -```c# +```csharp modelBuilder.Entity().HasData(new Blog { Id = 1, Timestamp = new DateTime(2020, 1, 1, 0, 0, 0) }); ``` @@ -129,7 +129,7 @@ If so, you'll have to change these to be UTC. In addition, all migrations code s The changes described above are far-reaching, and may break applications in various ways. You can upgrade to version 6.0 but opt out of the new mapping by enabling the `Npgsql.EnableLegacyTimestampBehavior` [AppContext switch](https://docs.microsoft.com/en-us/dotnet/api/system.appcontext?view=net-5.0). To do this and revert to the legacy timestamp behavior, add the following to your context's constructor, before any Npgsql or EF Core operations are invoked: -```c# +```csharp AppContext.SetSwitch("Npgsql.EnableLegacyTimestampBehavior", true); ``` @@ -141,7 +141,7 @@ When using NodaTime, PostgreSQL `tstzrange` columns are scaffolded as [Interval] PostgreSQL has special `infinity` and `-infinity` values for timestamps and dates, which are later and earlier than other value. Npgsql has supported mapping `DateTime.MaxValue` and `MinValue` to these infinity values via an `Convert Infinity DateTime` connection string parameter, which was disabled by default. This behavior is now on by default, since `DateTime.MaxValue` and `MinValue` are very rarely used as actual timestamps/dates, and the `Convert Infinity DateTime` parameter has been removed. To disable infinity conversions, add the following at the start of your application: -```c# +```csharp AppContext.SetSwitch("Npgsql.DisableDateTimeInfinityConversions", true); ``` @@ -151,14 +151,14 @@ AppContext.SetSwitch("Npgsql.DisableDateTimeInfinityConversions", true); Previously, it was possible to configure value converters for array/list properties with the general EF Core API: -```c# +```csharp modelBuilder.Entity.Property(e => e.ValueConvertedArray) .HasConversion(w => w.Select(x => x.Value).ToArray(), v => v.Select(x => new IntWrapper(x)).ToArray()); ``` This is no longer possible and will cause an exception to be thrown. Instead, use the new `HasPostgresArrayConversion` API, providing conversion lambdas for the array's *elements*: -```c# +```csharp modelBuilder.Entity.Property(e => e.ValueConvertedArray) .HasPostgresArrayConversion(w => w.Value, v => new IntWrapper(v)); ``` @@ -169,14 +169,14 @@ PostgreSQL 14 introduced [a new multirange type](https://www.postgresql.org/docs ### [Data Annotations](#tab/annotations) -```c# +```csharp [Column(TypeName = "int4range[]")] public NpgsqlRange[] SomeArrayOverIntNpgsqlRange { get; set;} ``` ### [Fluent API](#tab/fluent-api) -```c# +```csharp protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder diff --git a/docs/release-notes/7.0.md b/docs/release-notes/7.0.md index 275d81be1c..966ae01484 100644 --- a/docs/release-notes/7.0.md +++ b/docs/release-notes/7.0.md @@ -86,7 +86,7 @@ However, with the introduction of [pre-convention model configuration](https://d Default column collations involve the following code: -```c# +```csharp protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.UseDefaultColumnCollation(""); @@ -95,7 +95,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) To switch to the standard EF Core API, replace the code above with the following: -```c# +```csharp protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder) { configurationBuilder.Properties().UseCollation(""); diff --git a/docs/release-notes/8.0.md b/docs/release-notes/8.0.md index 56c55f966d..280bf8dc3c 100644 --- a/docs/release-notes/8.0.md +++ b/docs/release-notes/8.0.md @@ -10,7 +10,7 @@ One of PostgreSQL unique features as a relational database is its rich support f On to the code! You can now use any LINQ operator - or chain of operators - on top of a primitive array or list property. For example, the following queries for all blogs who have at least 3 tags starting with "x": -```c# +```csharp class Blog { ... @@ -37,7 +37,7 @@ Such complex translations rely on the PostgreSQL [`unnest`](https://www.postgres We can go further, querying for all blogs whose tags - or any of their posts' tags - contains a certain value: -```c# +```csharp var blogs = await ctx.Blogs .Where(b => b.Tags.Union(b.Posts.SelectMany(p => p.Tags)) .Contains("foo")) @@ -64,7 +64,7 @@ WHERE 'foo' IN ( But that's not all... The new primitive collection support works not just on columns, but also on parameterized lists. Previously, special and limited support existed for translating Contains over a parameterized list, as follows: -```c# +```csharp var ids = new[] { 1, 2, 3 }; var blogs = await ctx.Blogs @@ -74,7 +74,7 @@ var blogs = await ctx.Blogs This has now been extended to allow composing any LINQ operator. For example, the following query queries for any blogs which have at least one tag, where that tag starts with a list of possible prefixes: -```c# +```csharp var prefixes = new[] { "f", "b" }; var blogs = await ctx.Blogs @@ -102,7 +102,7 @@ Note the two usages of `unnest` here: one is used to expand the Tags column, whe Finally, support was added to *inline collections*, which are collections specified *inside* the query. For example, let's say that the list of tag prefixes in the previous query were always the same; in that case, we'd inline the prefixes variable as follows: -```c# +```csharp var blogs = await ctx.Blogs .Where(b => new[] { "f", "b" }.Any(p => b.Tags.Any(t => t.StartsWith(p)))) .ToListAsync(); @@ -138,7 +138,7 @@ Version 8.0 also brings support for EF7's [JSON columns](https://learn.microsoft You can read more on ToJson in the [Npgsql JSON doc page](../mapping/json.md), and in the [EF7 what's new docs](https://learn.microsoft.com/ef/core/what-is-new/ef-core-7.0/whatsnew#json-columns). Compared to the traditional Npgsql-specific POCO approach, a much wider range of LINQ queries can now be translated. For example, you can now compose LINQ operators over collections within JSON documents: -```c# +```csharp var blogs = await ctx.Customers .Where(b => b.Details.Orders.Any(o => o.Price > 8)) .ToListAsync(); @@ -162,7 +162,7 @@ Note the [`jsonb_to_recordset`](https://www.postgresql.org/docs/current/function Similarly, updates via EF's SaveChanges() are better, and can leverage *partial updating* to only patch the part of the JSON document which has changed. For example, let's assume that we load some customer with a JSON column, and change a single property within that JSON data: -```c# +```csharp var customer = await ctx.Customers.SingleAsync(c => c.Details.Name == "Foo"); customer.Details.Name = "Bar"; await ctx.SaveChangesAsync(); @@ -211,14 +211,14 @@ With EF 8.0 introducing first-class support for [primitive collections](https:// For example, the following Npgsql-specific code would configure value conversion for a property of type `MyType[]` to a PostgreSQL array of strings in EF Core 6 or 7: -```c# +```csharp modelBuilder.Entity().Property(b => b.ValueConvertedArray) .HasPostgresArrayConversion(x => x.ToString(), s => MyType.Parse(s)); ``` The same can now achieved with the following standard EF 8 code: -```c# +```csharp modelBuilder.Entity().PrimitiveCollection(b => b.ValueConvertedArray) .ElementType() .HasConversion(typeof(MyConverter)); diff --git a/docs/release-notes/9.0.md b/docs/release-notes/9.0.md index 09076c1ee6..7f4de3be21 100644 --- a/docs/release-notes/9.0.md +++ b/docs/release-notes/9.0.md @@ -13,7 +13,7 @@ Since version 7, the Npgsql ADO.NET provider has been moving to [NpgsqlDataSourc With version 9, `UseNpgsql()` becomes a single point for configuration, for both the EF and ADO.NET levels. EF can now internally set up an NpgsqlDataSource, automatically applying all the necessary configuration to it, and also exposes an API to allow users to apply arbitrary configuration to it as well: -```c# +```csharp builder.Services.AddDbContextPool(opt => opt.UseNpgsql( builder.Configuration.GetConnectionString("BloggingContext"), @@ -37,7 +37,7 @@ For more information, see the [getting started docs](../index.md). Previously, configuration around enums and plugins (NodaTime, NetTopologySuite) was complicated, requiring multiple setup actions at both the EF and the lower-level Npgsql layers. EF 9.0 improves the configuration story, allowing you to configure enums and plugins via a single EF gesture: -```c# +```csharp builder.Services.AddPooledDbContext(options => options.UseNpgsql( "", o => o.MapEnum("mood"))); @@ -67,7 +67,7 @@ As part of the improved enum configuration story in version 9.0 ([see above](#im If your application calls `UseNpgsql` with a simple connection string (rather than an NpgsqlDataSource), it simply needs to add a `MapEnum` call there: -```c# +```csharp builder.Services.AddDbContext(options => options.UseNpgsql( "", o => o.MapEnum("mood"))); From 7144ae5f8bb6b35197b26761bdf67d3b551c7196 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Fri, 20 Sep 2024 18:22:28 +0200 Subject: [PATCH 167/207] Remove gitter links --- docs/index.md | 1 - 1 file changed, 1 deletion(-) diff --git a/docs/index.md b/docs/index.md index b7709ba3ba..35f7665c6d 100644 --- a/docs/index.md +++ b/docs/index.md @@ -4,7 +4,6 @@ [![next patch](https://img.shields.io/myget/npgsql/v/Npgsql.EntityFrameworkCore.PostgreSQL.svg?label=next%20patch)](https://www.myget.org/feed/npgsql/package/nuget/Npgsql.EntityFrameworkCore.PostgreSQL) [![vnext](https://img.shields.io/myget/npgsql-vnext/vpre/Npgsql.EntityFrameworkCore.PostgreSQL.svg?label=vnext)](https://www.myget.org/feed/npgsql-vnext/package/nuget/Npgsql.EntityFrameworkCore.PostgreSQL) [![build](https://img.shields.io/github/actions/workflow/status/npgsql/efcore.pg/build.yml?branch=main)](https://github.com/npgsql/efcore.pg/actions) -[![gitter](https://img.shields.io/badge/gitter-join%20chat-brightgreen.svg)](https://gitter.im/npgsql/npgsql) 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](https://docs.microsoft.com/ef/core/index) apply here as well. If you're just getting started with EF Core, those docs are the best place to start. From 882ac405c0ff8710c4bab5e3417c6703792c7eb8 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Sun, 22 Sep 2024 15:02:30 +0200 Subject: [PATCH 168/207] Link to the 9.0 milestone issues --- docs/release-notes/9.0.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/release-notes/9.0.md b/docs/release-notes/9.0.md index 7f4de3be21..42ded75692 100644 --- a/docs/release-notes/9.0.md +++ b/docs/release-notes/9.0.md @@ -57,6 +57,10 @@ See [this post](https://www.cybertec-postgresql.com/en/unexpected-downsides-of-u Thanks to [@ChrisJollyAU](https://github.com/ChrisJollyAU) and [@Timovzl](https://github.com/Timovzl) for contributing this improvement! +## Other new features + +Version 9.0 contains other smaller features and bug fixes, [see the 9.0.0 milestone](https://github.com/npgsql/efcore.pg/milestone/61?closed=1) for the full list of Npgsql EF provider issues. + ## Breaking changes ### Enum mappings must now be configured at the EF level From f622444e2bd9e78b119dc6264b9c117bb6a7fc09 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Sat, 28 Sep 2024 08:20:14 +0200 Subject: [PATCH 169/207] Correct JSON translation SQL --- docs/mapping/json.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/mapping/json.md b/docs/mapping/json.md index 78db86bca7..c0c42245cc 100644 --- a/docs/mapping/json.md +++ b/docs/mapping/json.md @@ -255,7 +255,7 @@ EF.Functions.JsonTypeof(e.Customer.Age) .NET | SQL ------------------------------------------------------------------------------------- | ---- customer.RootElement.GetProperty("Name").GetString() | [customer->>'Name' = 'Joe'](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-OP-TABLE) -customer.RootElement.GetProperty("Orders")[1].GetProperty("Price").GetInt32() | [customer#>>'{Orders,0,Price}'\[1\] = 8](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-OP-TABLE) +customer.RootElement.GetProperty("Orders")[1].GetProperty("Price").GetInt32() | [CAST(customer #>> '{Orders,1,Price}' AS integer) = 8](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-OP-TABLE) customer.RootElement.GetProperty("Orders").GetArrayLength() | [jsonb_array_length(customer->'Orders'](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-PROCESSING-TABLE) EF.Functions.JsonContains(customer, @"{""Name"": ""Joe"", ""Age"": 25}")1 | [customer @> '{"Name": "Joe", "Age": 25}'](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) EF.Functions.JsonContained(@"{""Name"": ""Joe"", ""Age"": 25}", customer)1 | ['{"Name": "Joe", "Age": 25}' <@ customer](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) From 02e6a289c1a2a4c6afb1824ab3293bf3bbc2ac64 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Sat, 26 Oct 2024 16:08:30 +0200 Subject: [PATCH 170/207] Document array_remove translation See #3078 --- docs/mapping/array.md | 1 + docs/release-notes/9.0.md | 4 +++- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/docs/mapping/array.md b/docs/mapping/array.md index 09cecd5c19..47b1126301 100644 --- a/docs/mapping/array.md +++ b/docs/mapping/array.md @@ -37,6 +37,7 @@ array1.SequenceEqual(array2) | [array1 = array2](https://www.po arrayNonColumn.Contains(element) | [element = ANY(arrayNonColumn)](https://www.postgresql.org/docs/current/static/functions-comparisons.html#AEN21104) | Can use regular index arrayColumn.Contains(element) | [arrayColumn @> ARRAY\[element\]](https://www.postgresql.org/docs/current/functions-array.html#ARRAY-OPERATORS-TABLE) | Can use GIN index array.Append(element) | [array_append(array, element)](https://www.postgresql.org/docs/current/functions-array.html#ARRAY-FUNCTIONS-TABLE) | Added in 6.0 +array.Where(i => i != 8) | [array_remove(array, value)](https://www.postgresql.org/docs/current/functions-array.html#ARRAY-FUNCTIONS-TABLE) | Added in 9.0 array1.Concat(array2) | [array1 \|\| array2](https://www.postgresql.org/docs/current/functions-array.html#ARRAY-FUNCTIONS-TABLE) | Added in 6.0 array.IndexOf(element) | [array_position(array, element) - 1](https://www.postgresql.org/docs/current/functions-array.html#ARRAY-FUNCTIONS-TABLE) | Added in 6.0 array.IndexOf(element, startIndex) | [array_position(array, element, startIndex + 1) - 1](https://www.postgresql.org/docs/current/functions-array.html#ARRAY-FUNCTIONS-TABLE) | Added in 6.0 diff --git a/docs/release-notes/9.0.md b/docs/release-notes/9.0.md index 42ded75692..3e0b0ac3f7 100644 --- a/docs/release-notes/9.0.md +++ b/docs/release-notes/9.0.md @@ -59,7 +59,9 @@ Thanks to [@ChrisJollyAU](https://github.com/ChrisJollyAU) and [@Timovzl](https: ## Other new features -Version 9.0 contains other smaller features and bug fixes, [see the 9.0.0 milestone](https://github.com/npgsql/efcore.pg/milestone/61?closed=1) for the full list of Npgsql EF provider issues. +* Translate `array.Where(i => i != x)` to `array_remove(array, x)` + +See the [9.0.0 milestone](https://github.com/npgsql/efcore.pg/milestone/61?closed=1) for the full list of Npgsql EF provider issues. ## Breaking changes From 723369a97b5136f2e15f7022ed56804345416784 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Mon, 28 Oct 2024 08:53:50 +0100 Subject: [PATCH 171/207] Document DateOnly.DayNumber translations (#374) See https://github.com/npgsql/efcore.pg/pull/3333 --- docs/mapping/translations.md | 3 +++ docs/release-notes/9.0.md | 1 + 2 files changed, 4 insertions(+) diff --git a/docs/mapping/translations.md b/docs/mapping/translations.md index b5cfcf6469..2cd70beb1d 100644 --- a/docs/mapping/translations.md +++ b/docs/mapping/translations.md @@ -82,6 +82,9 @@ dateTime.Second | [date_part(' dateTime.Year | [date_part('year', dateTime)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | dateTime.ToUniversalTime | [dateTime::timestamptz](https://www.postgresql.org/docs/current/datatype-datetime.html#id-1.5.7.13.18.7) | Added in 6.0 dateTime.ToLocalTime | [dateTime::timestamp](https://www.postgresql.org/docs/current/datatype-datetime.html#id-1.5.7.13.18.7) | Added in 6.0 +dateOnly.DayNumber | [dateOnly - DATE '0001-01-01'](https://www.postgresql.org/docs/current/functions-datetime.html) | Added in 9.0 +DateOnly.FromDayNumber(x) | [DATE '0001-01-01' + x](https://www.postgresql.org/docs/current/functions-datetime.html) | Added in 9.0 +dateOnly1.DayNumber - dateOnly2.DayNumber | [dateOnly1 - dateOnly2](https://www.postgresql.org/docs/current/functions-datetime.html) | Added in 9.0 dateTimeOffset.DateTime | [dateTimeOffset AT TIME ZONE 'UTC'](https://www.postgresql.org/docs/current/functions-datetime.html#FUNCTIONS-DATETIME-ZONECONVERT) | Added in 6.0 dateTimeOffset.UtcDateTime | No PG operation (.NET-side conversion from DateTimeOffset to DateTime only) | Added in 6.0 dateTimeOffset.LocalDateTime | [dateTimeOffset::timestamp](https://www.postgresql.org/docs/current/datatype-datetime.html#id-1.5.7.13.18.7) | Added in 6.0 diff --git a/docs/release-notes/9.0.md b/docs/release-notes/9.0.md index 3e0b0ac3f7..acab181575 100644 --- a/docs/release-notes/9.0.md +++ b/docs/release-notes/9.0.md @@ -60,6 +60,7 @@ Thanks to [@ChrisJollyAU](https://github.com/ChrisJollyAU) and [@Timovzl](https: ## Other new features * Translate `array.Where(i => i != x)` to `array_remove(array, x)` +* Translate `DateOnly.DayNumber`, `DateOnly.FromDayNumber()` and simplify `dateOnly1.DayNumber - dateOnly2.DayNumber` to `dateOnly1 - dateOnly2`. See the [9.0.0 milestone](https://github.com/npgsql/efcore.pg/milestone/61?closed=1) for the full list of Npgsql EF provider issues. From bf3ba923c66e37e5c5770ce786e5c5312bcdbdbd Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Wed, 30 Oct 2024 12:35:05 +0100 Subject: [PATCH 172/207] Add note on EFCore.PG jsonpath support --- docs/release-notes/9.0.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/release-notes/9.0.md b/docs/release-notes/9.0.md index acab181575..ac84ccaf8b 100644 --- a/docs/release-notes/9.0.md +++ b/docs/release-notes/9.0.md @@ -61,6 +61,7 @@ Thanks to [@ChrisJollyAU](https://github.com/ChrisJollyAU) and [@Timovzl](https: * Translate `array.Where(i => i != x)` to `array_remove(array, x)` * Translate `DateOnly.DayNumber`, `DateOnly.FromDayNumber()` and simplify `dateOnly1.DayNumber - dateOnly2.DayNumber` to `dateOnly1 - dateOnly2`. +* Map the PostgreSQL `jsonpath` type to .NET string; this allows mapping to `jsonpath` columns. See the [9.0.0 milestone](https://github.com/npgsql/efcore.pg/milestone/61?closed=1) for the full list of Npgsql EF provider issues. From 9ec3c1c6201dc9153264675b700749e71501ec4e Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Wed, 30 Oct 2024 12:41:07 +0100 Subject: [PATCH 173/207] Some minor fixes to the EFCore.PG JSON page Fixes #376 --- docs/mapping/json.md | 50 ++++++++++++++++++++++---------------------- 1 file changed, 25 insertions(+), 25 deletions(-) diff --git a/docs/mapping/json.md b/docs/mapping/json.md index c0c42245cc..0444da082e 100644 --- a/docs/mapping/json.md +++ b/docs/mapping/json.md @@ -74,14 +74,14 @@ public class Customer public CustomerDetails Details { get; set; } } -public class CustomerDetails // Map to a JSON column in the table +public class CustomerDetails // Map to a JSON column in the table { public string Name { get; set; } public int Age { get; set; } public List Orders { get; set; } } -public class Order // Part of the JSON column +public class Order // Part of the JSON column { public decimal Price { get; set; } public string ShippingAddress { get; set; } @@ -104,13 +104,13 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) At this point you can interact with the Customer just like you would normally, and EF will seamlessly serialize and deserialize it to a JSON column in the database. You can also perform LINQ queries which reference properties inside the JSON document, and these will get translated to SQL. -## Traditional POCO mapping (deprecated) +### Legacy POCO mapping (deprecated) Before version 8.0 introduced support for EF's ToJson (owned entity mapping), the provider had its own support for JSON POCO mapping, by simply delegating serialization/deserialization to System.Text.Json; in this model, EF itself model the contents of the JSON document, and cannot take that structure into account for queries and updates. This approach can now be considered deprecated as it allows for less powerful mapping and supports less query types; using ToJson() is now the recommended way to map POCOs to JSON. -To use traditional POCO mapping, configure a property a mapping to map to a `jsonb` column as follows: +To use legacy POCO mapping, configure a property a mapping to map to a `jsonb` column as follows: -### [Data Annotations](#tab/data-annotations) +#### [Data Annotations](#tab/data-annotations) ```csharp public class Customer @@ -199,26 +199,26 @@ Console.WriteLine(someEntity.Customer.RootElement.GetProperty("Orders")[0].GetPr Note that when using this mapping, only limited forms of LINQ querying is supported; [see below](#querying-traditional-and-dom) for more details. -## Querying JSON columns (traditional JSON and DOM) +## Querying JSON columns (DOM and legacy POCO) > [!NOTE] -> The below does not apply if you are using ToJson (owned entity mapping). ToJson supports +> The below does not apply if you are using ToJson (owned entity mapping). ToJson mapping supports far more querying patterns than both legacy POCO and DOM and should be preferred. Saving and loading documents these documents wouldn't be much use without the ability to query them. You can express your queries via the same LINQ constructs you are already using in EF Core: -### [Classic POCO Mapping](#tab/poco) +### [JsonDocument Mapping](#tab/jsondocument) ```csharp var joes = context.CustomerEntries - .Where(e => e.Customer.Name == "Joe") + .Where(e => e.Customer.RootElement.GetProperty("Name").GetString() == "Joe") .ToList(); ``` -### [JsonDocument Mapping](#tab/jsondocument) +### [Legacy POCO Mapping](#tab/poco) ```csharp var joes = context.CustomerEntries - .Where(e => e.Customer.RootElement.GetProperty("Name").GetString() == "Joe") + .Where(e => e.Customer.Name == "Joe") .ToList(); ``` @@ -236,20 +236,6 @@ WHERE c.""Customer""->>'Name' = 'Joe' The following expression types and functions are translated: -### [POCO Mapping](#tab/poco) - -.NET | SQL ---------------------------------------------------------------------------------------- | ---- -customer.Name | [customer->>'Name'](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-OP-TABLE) -customer.Orders[1].Price | [customer#>>'{Orders,0,Price}'\[1\]](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-OP-TABLE) -customer.Orders.Length (or Count) | [jsonb_array_length(customer->'Orders')](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-PROCESSING-TABLE) -EF.Functions.JsonContains(customer, @"{""Name"": ""Joe"", ""Age"": 25}")1 | [customer @> '{"Name": "Joe", "Age": 25}'](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) -EF.Functions.JsonContained(@"{""Name"": ""Joe"", ""Age"": 25}", e.Customer)1 | ['{"Name": "Joe", "Age": 25}' <@ customer](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) -EF.Functions.JsonExists(e.Customer, "Age") | [customer ? 'Age'](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) -EF.Functions.JsonExistsAny(e.Customer, "Age", "Address") | [customer ?\| ARRAY\['Age','Address'\]](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) -EF.Functions.JsonExistsAll(e.Customer, "Age", "Address") | [customer ?& ARRAY\['Age','Address'\]](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) -EF.Functions.JsonTypeof(e.Customer.Age) | [jsonb_typeof(customer->'Age')](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-PROCESSING-TABLE) - ### [JsonDocument Mapping](#tab/jsondocument) .NET | SQL @@ -264,6 +250,20 @@ EF.Functions.JsonExistsAny(customer, "Age", "Address") EF.Functions.JsonExistsAll(customer, "Age", "Address") | [customer ?& ARRAY\['Age','Address'\]](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) EF.Functions.JsonTypeof(customer.GetProperty("Age")) == "number" | [jsonb_typeof(customer->'Age') = 'number'](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-PROCESSING-TABLE) +### [Legacy POCO Mapping](#tab/poco) + +.NET | SQL +--------------------------------------------------------------------------------------- | ---- +customer.Name | [customer->>'Name'](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-OP-TABLE) +customer.Orders[1].Price | [customer#>>'{Orders,0,Price}'\[1\]](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-OP-TABLE) +customer.Orders.Length (or Count) | [jsonb_array_length(customer->'Orders')](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-PROCESSING-TABLE) +EF.Functions.JsonContains(customer, @"{""Name"": ""Joe"", ""Age"": 25}")1 | [customer @> '{"Name": "Joe", "Age": 25}'](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) +EF.Functions.JsonContained(@"{""Name"": ""Joe"", ""Age"": 25}", e.Customer)1 | ['{"Name": "Joe", "Age": 25}' <@ customer](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) +EF.Functions.JsonExists(e.Customer, "Age") | [customer ? 'Age'](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) +EF.Functions.JsonExistsAny(e.Customer, "Age", "Address") | [customer ?\| ARRAY\['Age','Address'\]](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) +EF.Functions.JsonExistsAll(e.Customer, "Age", "Address") | [customer ?& ARRAY\['Age','Address'\]](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) +EF.Functions.JsonTypeof(e.Customer.Age) | [jsonb_typeof(customer->'Age')](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-PROCESSING-TABLE) + *** 1 JSON functions which accept a .NET object will not accept .NET scalar values. For example, to pass a scalar to `JsonContains` wrap it in a `JsonElement` or alternatively wrap it in a string. Note: a root level JSON string value requires quotes and escaping `@"""Joe"""`, just as any nested JSON string value would. From 9d92f056be34a879f4a132cf6dde17c5b416e502 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Mon, 18 Nov 2024 20:26:33 +0200 Subject: [PATCH 174/207] Move 6.0 to "out of support" and some general minor changes for 9.0 (#378) --- docs/release-notes/9.0.md | 7 ++----- docs/toc.yml | 6 +++--- 2 files changed, 5 insertions(+), 8 deletions(-) diff --git a/docs/release-notes/9.0.md b/docs/release-notes/9.0.md index ac84ccaf8b..8245bf561c 100644 --- a/docs/release-notes/9.0.md +++ b/docs/release-notes/9.0.md @@ -1,15 +1,12 @@ # 9.0 Release Notes -Npgsql.EntityFrameworkCore.PostgreSQL version 9.0 is under development; previews are available on [nuget.org](https://www.nuget.org/packages/Npgsql.EntityFrameworkCore.PostgreSQL). - -> [!NOTE] -> The following release notes and breaking changes are partial. More will be added nearer to the 9.0 final release. +Npgsql.EntityFrameworkCore.PostgreSQL version 9.0 is out and available on [nuget.org](https://www.nuget.org/packages/Npgsql.EntityFrameworkCore.PostgreSQL). ## Improved, unified configuration experience The Npgsql EF provider is built on top of the lower-level Npgsql ADO.NET provider; the configuration interface between these two layers was less than ideal, and configuration been more difficult than it should have been. For version 9.0, the configuration experience has been considerably improved. -Since version 7, the Npgsql ADO.NET provider has been moving to [NpgsqlDataSource](../../Npgsql/basic-usage.md#data-source) as the preferred way of configuration connections and obtaining them. At the EF level, it has been possible to pass an NpgsqlDataSource instance to `UseNpgsql()`; but this required that the user separately configure a data source and manage it. In addition, features such as plugins and enums require support from both the EF and ADO.NET layers, forcing users to perform multiple setup actions at the different layers. +Since version 7, the Npgsql ADO.NET provider has been moving to [NpgsqlDataSource](../../Npgsql/basic-usage.md#data-source) as the preferred way of configuring connections and obtaining them. At the EF level, it has been possible to pass an NpgsqlDataSource instance to `UseNpgsql()`; but this required that the user separately configure a data source and manage it. In addition, features such as plugins and enums require support from both the EF and ADO.NET layers, forcing users to perform multiple setup actions at the different layers. With version 9, `UseNpgsql()` becomes a single point for configuration, for both the EF and ADO.NET levels. EF can now internally set up an NpgsqlDataSource, automatically applying all the necessary configuration to it, and also exposes an API to allow users to apply arbitrary configuration to it as well: diff --git a/docs/toc.yml b/docs/toc.yml index b4ed54fef4..86a4377812 100644 --- a/docs/toc.yml +++ b/docs/toc.yml @@ -2,16 +2,16 @@ href: index.md - name: Release notes items: - - name: "9.0 (prerelease)" + - name: "9.0" href: release-notes/9.0.md - name: "8.0" href: release-notes/8.0.md - - name: "6.0" - href: release-notes/6.0.md - name: Out of support items: - name: "7.0" href: release-notes/7.0.md + - name: "6.0" + href: release-notes/6.0.md - name: "5.0" href: release-notes/5.0.md - name: "3.1" From e9d1123528d01db374cc8bdecadc0b79ebd552c0 Mon Sep 17 00:00:00 2001 From: Obed Kooijman Date: Sun, 8 Dec 2024 17:34:22 +0100 Subject: [PATCH 175/207] Some corrections regarding contributors for 9.0.0 (#384) --- docs/release-notes/9.0.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/docs/release-notes/9.0.md b/docs/release-notes/9.0.md index 8245bf561c..99908d405d 100644 --- a/docs/release-notes/9.0.md +++ b/docs/release-notes/9.0.md @@ -92,6 +92,7 @@ A big thank you to all the following people who contributed to the 9.0 release! Contributor | Assigned issues ------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------ -[@roji](https://github.com/roji) | [34](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A8.0.0+is%3Aclosed+assignee%3Aroji) -[@ChrisJollyAU](https://github.com/ChrisJollyAU) | [1](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A8.0.0+is%3Aclosed+assignee%3AChrisJollyAU) -[@Timovzl](https://github.com/Timovzl) | [1](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A8.0.0+is%3Aclosed+assignee%3ATimovzl) +[@roji](https://github.com/roji) | [28](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A9.0.0+is%3Aclosed+assignee%3Aroji) +[@ChrisJollyAU](https://github.com/ChrisJollyAU) | [2](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A9.0.0+is%3Aclosed+assignee%3AChrisJollyAU) +[@Timovzl](https://github.com/Timovzl) | [1](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A9.0.0+is%3Aclosed+assignee%3ATimovzl) +[@WhatzGames](https://github.com/WhatzGames) | [1](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A9.0.0+is%3Aclosed+assignee%3AWhatzGames) From be4bcc5abb890a42b9c93c1742218d7ccc012e0b Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Tue, 14 Jan 2025 18:00:52 +0100 Subject: [PATCH 176/207] Amend getting started example for externally provided NpgsqlDataSource (#386) See https://github.com/npgsql/npgsql/issues/4523#issuecomment-2590392427 --- docs/index.md | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/docs/index.md b/docs/index.md index 35f7665c6d..359b9a6c1b 100644 --- a/docs/index.md +++ b/docs/index.md @@ -142,7 +142,7 @@ builder.Services.AddDbContextPool(opt => ### Using an external NpgsqlDataSource -If you're using a version of EF prior to 9.0, the above configuration methods aren't available. You can still create an `NpgsqlDataSource` yourself, and then pass it EF's `UseNpgsql()`: +If you're using a version of EF prior to 9.0, the above configuration methods aren't available. You can still create an NpgsqlDataSource yourself, and then pass it to EF's `UseNpgsql()`: ```csharp var dataSourceBuilder = new NpgsqlDataSourceBuilder(builder.Configuration.GetConnectionString("BloggingContext")); @@ -150,9 +150,15 @@ dataSourceBuilder.MapEnum(); dataSourceBuilder.UseNodaTime(); var dataSource = dataSourceBuilder.Build(); -builder.Services.AddDbContextPool(opt => opt.UseNpgsql(dataSource)); +builder.Services.AddDbContextPool(opt => opt + .UseNpgsql(dataSource, o => o + .SetPostgresVersion(13, 0) + .UseNodaTime() + .MapEnum("mood"))); ``` +Note that when using an external NpgsqlDataSource, you need to configure mappings and plugins at both levels yourself - both on the NpgsqlDataSource and at the EF provider level. + ## 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: From 9eb6bb28c254af658173b1ee628083b2aa434a55 Mon Sep 17 00:00:00 2001 From: Yoh Deadfall Date: Sat, 22 Mar 2025 00:11:42 +0300 Subject: [PATCH 177/207] Fixed type name casing (#399) --- docs/mapping/full-text-search.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/mapping/full-text-search.md b/docs/mapping/full-text-search.md index 090bc70006..c3f4c0257a 100644 --- a/docs/mapping/full-text-search.md +++ b/docs/mapping/full-text-search.md @@ -168,7 +168,7 @@ EF.Functions.PhraseToTsQuery(string) | [p EF.Functions.PhraseToTsQuery("english", string) | [phraseto_tsquery('english'::regconfig, string)](https://www.postgresql.org/docs/current/static/textsearch-controls.html#TEXTSEARCH-PARSING-QUERIES) EF.Functions.WebSearchToTsQuery(string) | [websearch_to_tsquery(string)](https://www.postgresql.org/docs/current/static/textsearch-controls.html#TEXTSEARCH-PARSING-QUERIES) EF.Functions.WebSearchToTsQuery("english", string) | [websearch_to_tsquery('english'::regconfig, string)](https://www.postgresql.org/docs/current/static/textsearch-controls.html#TEXTSEARCH-PARSING-QUERIES) -EF.functions.ArrayToTsVector(new[] { "a", "b" }) | [array_to_tsvector(ARRAY\['a', 'b'\])](https://www.postgresql.org/docs/current/functions-textsearch.html#TEXTSEARCH-FUNCTIONS-TABLE) +EF.Functions.ArrayToTsVector(new[] { "a", "b" }) | [array_to_tsvector(ARRAY\['a', 'b'\])](https://www.postgresql.org/docs/current/functions-textsearch.html#TEXTSEARCH-FUNCTIONS-TABLE) NpgsqlTsVector.Parse(string) | [CAST(string AS tsvector)](https://www.postgresql.org/docs/current/static/sql-expressions.html#SQL-SYNTAX-TYPE-CASTS) NpgsqlTsQuery.Parse(string) | [CAST(queryString AS tsquery)](https://www.postgresql.org/docs/current/static/sql-expressions.html#SQL-SYNTAX-TYPE-CASTS) tsvector.Matches(string) | [tsvector @@ plainto_tsquery(string)](https://www.postgresql.org/docs/current/static/textsearch-intro.html#TEXTSEARCH-MATCHING) From 5bbe5e641f9676288c38443bebfbf6da00a9c7ce Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Tue, 22 Apr 2025 11:44:32 +0200 Subject: [PATCH 178/207] Document fuzzy text search translations (#405) Closes #404 --- docs/mapping/translations.md | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/docs/mapping/translations.md b/docs/mapping/translations.md index 2cd70beb1d..8a2f84015c 100644 --- a/docs/mapping/translations.md +++ b/docs/mapping/translations.md @@ -219,9 +219,6 @@ EF.Functions.Set7BitMac8(macaddr8) | [macaddr8_set7bit(macaddr8)]( The below translations provide functionality for determining the similarity of alphanumeric text based on trigram matching, using the [`pg_trgm`](https://www.postgresql.org/docs/current/pgtrgm.html) extension which is bundled with standard PostgreSQL distributions. All the below parameters are strings. -> [!NOTE] -> Prior to version 6.0, to use these translations, your project must depend on the [Npgsql.EntityFrameworkCore.PostgreSQL.Trigrams](https://www.nuget.org/packages/Npgsql.EntityFrameworkCore.PostgreSQL.Trigrams/) package, and call `UseTrigrams()` in your `OnModelConfiguring`. - .NET | SQL ----------------------------------------------------------------- | -------------------- EF.Functions.TrigramsShow(s) | show_trgm(s) @@ -239,6 +236,22 @@ EF.Functions.TrigramsWordSimilarityDistanceInverted(s1, s2) | s1 <-> EF.Functions.TrigramsStrictWordSimilarityDistance(s1, s2) | s1 <<<-> s2 EF.Functions.TrigramsStrictWordSimilarityDistanceInverted(s1, s2) | s1 <->>> s2 +## Fuzzy string match functions + +The below translations provide functionality for determining similarities and distance between strings, using the [`pg_trgm`](https://www.postgresql.org/docs/current/pgtrgm.html) extension which is bundled with standard PostgreSQL distributions. + +.NET | SQL +------------------------------------------------------------------------------------------------------ | -------------------- +EF.Functions.FuzzyStringMatchSoundex(text) | [soundex(text)](https://www.postgresql.org/docs/current/fuzzystrmatch.html#FUZZYSTRMATCH-SOUNDEX) +EF.Functions.FuzzyStringMatchDifference(source, target) | [difference(source, target)](https://www.postgresql.org/docs/current/fuzzystrmatch.html#FUZZYSTRMATCH-SOUNDEX) +EF.Functions.FuzzyStringMatchLevenshtein(source, target) | [levenshtein(source, target)](https://www.postgresql.org/docs/current/fuzzystrmatch.html#FUZZYSTRMATCH-LEVENSHTEIN) +EF.Functions.FuzzyStringMatchLevenshtein(source, target, ins_cost, del_cost, sub_cost) | [levenshtein(source, target, ins_cost, del_cost, sub_cost)](https://www.postgresql.org/docs/current/fuzzystrmatch.html#FUZZYSTRMATCH-LEVENSHTEIN) +EF.Functions.FuzzyStringMatchLevenshteinLessEqual(source, target, max_d) | [levenshtein(source, target, max_d)](https://www.postgresql.org/docs/current/fuzzystrmatch.html#FUZZYSTRMATCH-LEVENSHTEIN) +EF.Functions.FuzzyStringMatchLevenshteinLessEqual(source, target, ins_cost, del_cost, sub_cost, max_d) | [levenshtein(source, target, ins_cost, del_cost, sub_cost, max_d)](https://www.postgresql.org/docs/current/fuzzystrmatch.html#FUZZYSTRMATCH-LEVENSHTEIN) +EF.Functions.FuzzyStringMatchMetaphone(text, max_output_length) | [metaphone(text, max_output_length)](https://www.postgresql.org/docs/current/fuzzystrmatch.html#FUZZYSTRMATCH-METAPHONE) +EF.Functions.FuzzyStringMatchDoubleMetaphone(text) | [dmetaphone(text)](https://www.postgresql.org/docs/current/fuzzystrmatch.html#FUZZYSTRMATCH-METAPHONE) +EF.Functions.FuzzyStringMatchDoubleMetaphoneAlt(text) | [dmetaphone_alt(text)](https://www.postgresql.org/docs/current/fuzzystrmatch.html#FUZZYSTRMATCH-METAPHONE) + ## LTree functions The below translations are for working with label trees from the PostgreSQL [`ltree`](https://www.postgresql.org/docs/current/ltree.html) extension. Use the type to represent ltree and invoke methods on it in EF Core LINQ queries. From 0d4895fa268aebeb757e99a396a424dedb281a18 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Mon, 7 Jul 2025 12:27:16 +0200 Subject: [PATCH 179/207] Add EFCore.PG 10 release notes plus other changes (#412) * Document new virtual generated column support * Document new Guid.CreateVersion7 translation * Go over docs and remove notes on old EF versions --- docs/mapping/full-text-search.md | 77 ++---------------- docs/mapping/range.md | 7 +- docs/mapping/translations.md | 85 +++++++++----------- docs/misc/collations-and-case-sensitivity.md | 12 +-- docs/modeling/concurrency.md | 11 +-- docs/modeling/generated-properties.md | 49 +++-------- docs/modeling/indexes.md | 6 -- docs/modeling/tables.md | 4 +- docs/release-notes/10.0.md | 32 ++++++++ docs/toc.yml | 2 + 10 files changed, 95 insertions(+), 190 deletions(-) create mode 100644 docs/release-notes/10.0.md diff --git a/docs/mapping/full-text-search.md b/docs/mapping/full-text-search.md index c3f4c0257a..890573fc6e 100644 --- a/docs/mapping/full-text-search.md +++ b/docs/mapping/full-text-search.md @@ -34,14 +34,7 @@ public class Product } ``` -Setting up the column to be auto-updated depends on your PostgreSQL version. On PostgreSQL 12 and above, the column can be a simple [generated column](../modeling/generated-properties.md#computed-columns), and version 5.0.0 contains sugar for setting that up. In previous versions, you must manually set up database triggers that update the column instead. - -#### [PostgreSQL 12+](#tab/pg12) - -> [!NOTE] -> The below only works on PostgreSQL 12 and version 5.0.0 of the EF Core provider. - -The following will set up a generated `tsvector` column, over which you can easily create an index: +Then, configure the property to be a [stored generated column](../modeling/generated-properties.md#computed-generated-columns): the provider has an API for setting that up: ```csharp protected override void OnModelCreating(ModelBuilder modelBuilder) @@ -56,48 +49,9 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) } ``` -#### [Older Versions](#tab/pg-lt-12) - -First, modify the `OnModelCreating()` of your context class to add an index as follows: - -```csharp -protected override void OnModelCreating(ModelBuilder modelBuilder) -{ - modelBuilder.Entity() - .HasIndex(p => p.SearchVector) - .HasMethod("GIN"); // Index method on the search vector (GIN or GIST) -} -``` +Note that `HasGeneratedTsVectorColumn()` is simply a bit of sugar of EF's standard `HasComputedColumnSql()`; if there's anything you need which isn't covered by `HasGeneratedTsVectorColumn()`, simply use `HasComputedColumnSql()`. -Now generate a migration (`dotnet ef migrations add ....`), and open it with your favorite editor, adding the following: - -```csharp -public partial class CreateProductTable : Migration -{ - protected override void Up(MigrationBuilder migrationBuilder) - { - // Migrations for creation of the column and the index will appear here, all we need to do is set up the trigger to update the column: - - migrationBuilder.Sql( - @"CREATE TRIGGER product_search_vector_update BEFORE INSERT OR UPDATE - ON ""Products"" FOR EACH ROW EXECUTE PROCEDURE - tsvector_update_trigger(""SearchVector"", 'pg_catalog.english', ""Name"", ""Description"");"); - - // If you were adding a tsvector to an existing table, you should populate the column using an UPDATE - // migrationBuilder.Sql("UPDATE \"Products\" SET \"Name\" = \"Name\";"); - } - - protected override void Down(MigrationBuilder migrationBuilder) - { - // Migrations for dropping of the column and the index will appear here, all we need to do is drop the trigger: - migrationBuilder.Sql("DROP TRIGGER product_search_vector_update"); - } -} -``` - -*** - -Once your auto-updated `tsvector` column is set up, any inserts or updates on the `Products` table will now update the `SearchVector` column and maintain it automatically. You can query it as follows: +Once your generated `tsvector` column is set up, any inserts or updates on the `Products` table will update the `SearchVector` column and maintain it automatically. You can query it as follows: ```csharp var context = new ProductDbContext(); @@ -108,9 +62,7 @@ var npgsql = context.Products ### Method 2: Expression index -Version 5.0.0 of the provider includes sugar for defining the appropriate expression index; if you're using an older version, you'll have to define a raw SQL migration yourself. - -#### [Version 5.0.0](#tab/v5) +If you prefer to have an expression index rather than a generated column, use the following API to do so: ```csharp modelBuilder.Entity() @@ -119,23 +71,6 @@ modelBuilder.Entity() .IsTsVectorExpressionIndex("english"); ``` -#### [Older Versions](#tab/lt-v5) - -Create a migration which will contain the index creation SQL (`dotnet ef migrations add ...`). At this point, open the generated migration with your editor and add the following: - -```csharp -protected override void Up(MigrationBuilder migrationBuilder) -{ - migrationBuilder.Sql(@"CREATE INDEX fts_idx ON ""Product"" USING GIN (to_tsvector('english', ""Name"" || ' ' || ""Description""));"); -} - -protected override void Down(MigrationBuilder migrationBuilder) - migrationBuilder.Sql(@"DROP INDEX fts_idx;"); -} -``` - -*** - Once the index is created on the `Title` and `Description` columns, you can query as follows: ```csharp @@ -148,9 +83,9 @@ var npgsql = context.Products ## Computed column over JSON columns -Starting with 7.0, the provider can also create computed `tsvector` columns over JSON columns. Simply use `HasGeneratedTsVectorColumn()` as shown above, and when applied to JSON columns, the provider will automatically generate [`json_to_tsvector/jsonb_to_tsvector`](https://www.postgresql.org/docs/current/functions-textsearch.html#TEXTSEARCH-FUNCTIONS-TABLE) as appropriate. +The provider can also create computed `tsvector` columns over JSON columns. Simply use `HasGeneratedTsVectorColumn()` as shown above, and when applied to JSON columns, the provider will automatically generate [`json_to_tsvector/jsonb_to_tsvector`](https://www.postgresql.org/docs/current/functions-textsearch.html#TEXTSEARCH-FUNCTIONS-TABLE) as appropriate. -Note that this will pass the filter `all` to these functions, meaning that all values in the JSON document will be included. To customize the filter - or to create the computed column on older versions of the provider - simply specify the function yourself via [`HasComputedColumnSql`](https://docs.microsoft.com/ef/core/modeling/generated-properties?tabs=data-annotations#computed-columns). +Note that this will pass the filter `all` to these functions, meaning that all values in the JSON document will be included. To customize the filter - or to create the computed column on older versions of the provider - simply specify the function yourself via [`HasComputedColumnSql`](https://docs.microsoft.com/ef/core/modeling/generated-properties?tabs=data-annotations#computed-generated-columns). ## Operation translation diff --git a/docs/mapping/range.md b/docs/mapping/range.md index 0255d08921..80393c915b 100644 --- a/docs/mapping/range.md +++ b/docs/mapping/range.md @@ -2,7 +2,7 @@ PostgreSQL has the unique feature of supporting [*range data types*](https://www.postgresql.org/docs/current/static/rangetypes.html). Ranges represent a range of numbers, dates or other data types, and allow you to easily query ranges which contain a value, perform set operations (e.g. query ranges which contain other ranges), and other similar operations. The range operations supported by PostgreSQL are listed [in this page](https://www.postgresql.org/docs/current/static/functions-range.html). The Npgsql EF Core provider allows you to seamlessly map PostgreSQL ranges, and even perform operations on them that get translated to SQL for server evaluation. -In addition, PostgreSQL 14 introduced *multiranges*, which are basically sorted arrays of non-overlapping ranges with set-theoretic operations defined over them. Most range operators also work on multiranges, and they have a few functions of their own. Multirange support in the EF Core provider was introduced in version 6.0.0. +In addition, PostgreSQL 14 introduced *multiranges*, which are basically sorted arrays of non-overlapping ranges with set-theoretic operations defined over them. Most range operators also work on multiranges, and they have a few functions of their own. ## Ranges @@ -45,9 +45,6 @@ This will cause the appropriate [`CREATE TYPE ... AS RANGE`](https://www.postgre ## Multiranges -> [!NOTE] -> This feature was introduced in version 6.0 - Npgsql maps arrays or lists of `NpgsqlRange` to PostgreSQL multiranges: ```csharp @@ -99,4 +96,4 @@ range1.Merge(range2) | [range_merge(range1, range2)](https://ww multirange.Merge() | [range_merge(multirange)](https://www.postgresql.org/docs/current/functions-range.html#MULTIRANGE-FUNCTIONS-TABLE) ranges.RangeAgg() | [range_agg(ranges)](https://www.postgresql.org/docs/current/functions-aggregate.html) ranges.RangeIntersectAgg() | [range_intersect_agg(ranges)](https://www.postgresql.org/docs/current/functions-aggregate.html) -multiranges.RangeIntersectAgg() | [range_intersect_agg(multiranges)](https://www.postgresql.org/docs/current/functions-aggregate.html) | Added in 7.0, See [Aggregate functions](translations.md#aggregate-functions). +multiranges.RangeIntersectAgg() | [range_intersect_agg(multiranges)](https://www.postgresql.org/docs/current/functions-aggregate.html) | See [Aggregate functions](translations.md#aggregate-functions). diff --git a/docs/mapping/translations.md b/docs/mapping/translations.md index 8a2f84015c..c1e5248616 100644 --- a/docs/mapping/translations.md +++ b/docs/mapping/translations.md @@ -8,7 +8,7 @@ The Npgsql-specific translations are listed below. Some areas, such as [full-tex .NET | SQL | Notes ------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- | -------- -EF.Functions.Collate(operand, collation) | operand COLLATE collation | Added in 5.0 +EF.Functions.Collate(operand, collation) | operand COLLATE collation EF.Functions.Like(matchExpression, pattern) | matchExpression LIKE pattern EF.Functions.Like(matchExpression, pattern, escapeCharacter) | matchExpression LIKE pattern ESCAPE escapeCharacter EF.Functions.ILike(matchExpression, pattern) | [matchExpression ILIKE pattern](../misc/collations-and-case-sensitivity.md) @@ -20,9 +20,9 @@ string.IsNullOrWhiteSpace(value) | value IS NULL OR stringValue.CompareTo(strB) | CASE WHEN stringValue = strB THEN 0 ... END stringValue.Contains(value) | stringValue LIKE %value% stringValue.EndsWith(value) | stringValue LIKE '%' \|\| value -stringValue.FirstOrDefault() | substr(stringValue, 1, 1) | Added in 5.0 +stringValue.FirstOrDefault() | substr(stringValue, 1, 1) stringValue.IndexOf(value) | strpos(stringValue, value) - 1 -stringValue.LastOrDefault() | substr(stringValue, length(stringValue), 1) | Added in 5.0 +stringValue.LastOrDefault() | substr(stringValue, length(stringValue), 1) stringValue.Length | length(stringValue) stringValue.PadLeft(length) | lpad(stringValue, length) stringValue.PadLeft(length, char) | lpad(stringValue, length, char) @@ -42,11 +42,11 @@ stringValue.TrimStart(trimChar) | ltrim(stringValu EF.Functions.Reverse(value) | reverse(value) Regex.IsMatch(stringValue, "^A+") | [stringValue ~ '^A+'](http://www.postgresql.org/docs/current/static/functions-matching.html#FUNCTIONS-POSIX-REGEXP) (with options) Regex.IsMatch(stringValue, "^A+", regexOptions) | [stringValue ~ '^A+'](http://www.postgresql.org/docs/current/static/functions-matching.html#FUNCTIONS-POSIX-REGEXP) (with options) -string.Join(", ", a, b) | [concat_ws(', ', a, b)](https://www.postgresql.org/docs/current/functions-string.html#FUNCTIONS-STRING-OTHER) | Added in 7.0 (previously array_to_string) +string.Join(", ", a, b) | [concat_ws(', ', a, b)](https://www.postgresql.org/docs/current/functions-string.html#FUNCTIONS-STRING-OTHER) string.Join(", ", array) | [array_to_string(array, ', ', '')](https://www.postgresql.org/docs/current/functions-array.html#ARRAY-FUNCTIONS-TABLE) -string.Join(", ", agg_strings) | [string_agg(agg_strings, ', ')](https://www.postgresql.org/docs/current/functions-aggregate.html#FUNCTIONS-AGGREGATE-TABLE) | Added in 7.0, see [Aggregate functions](#aggregate-functions). -EF.Functions.StringToArray(s, "\|") | [string_agg(s, '\|')](https://www.postgresql.org/docs/current/functions-string.html#FUNCTION-STRING-TO-ARRAY) | Added in 8.0 -EF.Functions.StringToArray(s, "\|", "FOO") | [string_agg(s, '\|', 'FOO')](https://www.postgresql.org/docs/current/functions-string.html#FUNCTION-STRING-TO-ARRAY) | Added in 8.0 +string.Join(", ", agg_strings) | [string_agg(agg_strings, ', ')](https://www.postgresql.org/docs/current/functions-aggregate.html#FUNCTIONS-AGGREGATE-TABLE) | See [Aggregate functions](#aggregate-functions). +EF.Functions.StringToArray(s, "\|") | [string_agg(s, '\|')](https://www.postgresql.org/docs/current/functions-string.html#FUNCTION-STRING-TO-ARRAY) +EF.Functions.StringToArray(s, "\|", "FOO") | [string_agg(s, '\|', 'FOO')](https://www.postgresql.org/docs/current/functions-string.html#FUNCTION-STRING-TO-ARRAY) ## Date and time functions @@ -59,12 +59,12 @@ EF.Functions.StringToArray(s, "\|", "FOO") | [string_agg(s, ' .NET | SQL | Notes ----------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- | -------- -DateTime.UtcNow (6.0+) | [now()](https://www.postgresql.org/docs/current/functions-datetime.html) | See 6.0 release notes -DateTime.Now (6.0+) | [now()::timestamp](https://www.postgresql.org/docs/current/functions-datetime.html) | See 6.0 release notes -DateTime.Today (6.0+) | [date_trunc('day', now()::timestamp)](https://www.postgresql.org/docs/current/functions-datetime.html) | See 6.0 release notes -DateTime.UtcNow (legacy) | [now() AT TIME ZONE 'UTC'](https://www.postgresql.org/docs/current/functions-datetime.html) | See 6.0 release notes -DateTime.Now (legacy) | [now()](https://www.postgresql.org/docs/current/functions-datetime.html) | See 6.0 release notes -DateTime.Today (legacy) | [date_trunc('day', now())](https://www.postgresql.org/docs/current/functions-datetime.html) | See 6.0 release notes +DateTime.UtcNow (6.0+) | [now()](https://www.postgresql.org/docs/current/functions-datetime.html) | +DateTime.Now (6.0+) | [now()::timestamp](https://www.postgresql.org/docs/current/functions-datetime.html) | +DateTime.Today (6.0+) | [date_trunc('day', now()::timestamp)](https://www.postgresql.org/docs/current/functions-datetime.html) | +DateTime.UtcNow (legacy) | [now() AT TIME ZONE 'UTC'](https://www.postgresql.org/docs/current/functions-datetime.html) | +DateTime.Now (legacy) | [now()](https://www.postgresql.org/docs/current/functions-datetime.html) | +DateTime.Today (legacy) | [date_trunc('day', now())](https://www.postgresql.org/docs/current/functions-datetime.html) | dateTime.AddDays(1) | [dateTime + INTERVAL '1 days'](https://www.postgresql.org/docs/current/functions-datetime.html#OPERATORS-DATETIME-TABLE) | dateTime.AddHours(value) | [dateTime + INTERVAL '1 hours'](https://www.postgresql.org/docs/current/functions-datetime.html#OPERATORS-DATETIME-TABLE) | dateTime.AddMinutes(1) | [dateTime + INTERVAL '1 minutes'](https://www.postgresql.org/docs/current/functions-datetime.html#OPERATORS-DATETIME-TABLE) | @@ -80,35 +80,35 @@ dateTime.Minute | [date_part(' dateTime.Month | [date_part('month', dateTime)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | dateTime.Second | [date_part('second', dateTime)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | dateTime.Year | [date_part('year', dateTime)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | -dateTime.ToUniversalTime | [dateTime::timestamptz](https://www.postgresql.org/docs/current/datatype-datetime.html#id-1.5.7.13.18.7) | Added in 6.0 -dateTime.ToLocalTime | [dateTime::timestamp](https://www.postgresql.org/docs/current/datatype-datetime.html#id-1.5.7.13.18.7) | Added in 6.0 +dateTime.ToUniversalTime | [dateTime::timestamptz](https://www.postgresql.org/docs/current/datatype-datetime.html#id-1.5.7.13.18.7) | +dateTime.ToLocalTime | [dateTime::timestamp](https://www.postgresql.org/docs/current/datatype-datetime.html#id-1.5.7.13.18.7) | dateOnly.DayNumber | [dateOnly - DATE '0001-01-01'](https://www.postgresql.org/docs/current/functions-datetime.html) | Added in 9.0 DateOnly.FromDayNumber(x) | [DATE '0001-01-01' + x](https://www.postgresql.org/docs/current/functions-datetime.html) | Added in 9.0 dateOnly1.DayNumber - dateOnly2.DayNumber | [dateOnly1 - dateOnly2](https://www.postgresql.org/docs/current/functions-datetime.html) | Added in 9.0 -dateTimeOffset.DateTime | [dateTimeOffset AT TIME ZONE 'UTC'](https://www.postgresql.org/docs/current/functions-datetime.html#FUNCTIONS-DATETIME-ZONECONVERT) | Added in 6.0 -dateTimeOffset.UtcDateTime | No PG operation (.NET-side conversion from DateTimeOffset to DateTime only) | Added in 6.0 -dateTimeOffset.LocalDateTime | [dateTimeOffset::timestamp](https://www.postgresql.org/docs/current/datatype-datetime.html#id-1.5.7.13.18.7) | Added in 6.0 +dateTimeOffset.DateTime | [dateTimeOffset AT TIME ZONE 'UTC'](https://www.postgresql.org/docs/current/functions-datetime.html#FUNCTIONS-DATETIME-ZONECONVERT) | +dateTimeOffset.UtcDateTime | No PG operation (.NET-side conversion from DateTimeOffset to DateTime only) | +dateTimeOffset.LocalDateTime | [dateTimeOffset::timestamp](https://www.postgresql.org/docs/current/datatype-datetime.html#id-1.5.7.13.18.7) | timeSpan.Days | [floor(date_part('day', timeSpan))::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | timeSpan.Hours | [floor(date_part('hour', timeSpan))::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | timeSpan.Minutes | [floor(date_part('minute', timeSpan))::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | timeSpan.Seconds | [floor(date_part('second', timeSpan))::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | timeSpan.Milliseconds | [floor(date_part('millisecond', timeSpan))::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | timeSpan.Milliseconds | [floor(date_part('millisecond', timeSpan))::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | -timeSpan.TotalMilliseconds | [date_part('epoch', interval) / 0.001](https://www.postgresql.org/docs/current/functions-datetime.html) | Added in 6.0 -timeSpan.TotalSeconds | [date_part('epoch', interval)](https://www.postgresql.org/docs/current/functions-datetime.html) | Added in 6.0 -timeSpan.TotalMinutes | [date_part('epoch', interval) / 60.0](https://www.postgresql.org/docs/current/functions-datetime.html) | Added in 6.0 -timeSpan.TotalDays | [date_part('epoch', interval) / 86400.0](https://www.postgresql.org/docs/current/functions-datetime.html) | Added in 6.0 -timeSpan.TotalHours | [date_part('epoch', interval) / 3600.0](https://www.postgresql.org/docs/current/functions-datetime.html) | Added in 6.0 +timeSpan.TotalMilliseconds | [date_part('epoch', interval) / 0.001](https://www.postgresql.org/docs/current/functions-datetime.html) | +timeSpan.TotalSeconds | [date_part('epoch', interval)](https://www.postgresql.org/docs/current/functions-datetime.html) | +timeSpan.TotalMinutes | [date_part('epoch', interval) / 60.0](https://www.postgresql.org/docs/current/functions-datetime.html) | +timeSpan.TotalDays | [date_part('epoch', interval) / 86400.0](https://www.postgresql.org/docs/current/functions-datetime.html) | +timeSpan.TotalHours | [date_part('epoch', interval) / 3600.0](https://www.postgresql.org/docs/current/functions-datetime.html) | dateTime1 - dateTime2 | [dateTime1 - dateTime2](https://www.postgresql.org/docs/current/functions-datetime.html#OPERATORS-DATETIME-TABLE) | -TimeZoneInfo.ConvertTimeBySystemTimeZoneId(utcDateTime, timezone) | [utcDateTime AT TIME ZONE timezone](https://www.postgresql.org/docs/current/functions-datetime.html#FUNCTIONS-DATETIME-ZONECONVERT) | Added in 6.0, only for timestamptz columns -TimeZoneInfo.ConvertTimeToUtc(nonUtcDateTime) | [nonUtcDateTime::timestamptz](https://www.postgresql.org/docs/current/functions-datetime.html) | Added in 6.0, only for timestamp columns -DateTime.SpecifyKind(utcDateTime, DateTimeKind.Unspecified) | [utcDateTime AT TIME ZONE 'UTC'](https://www.postgresql.org/docs/current/functions-datetime.html#FUNCTIONS-DATETIME-ZONECONVERT) | Added in 6.0, only for timestamptz columns -DateTime.SpecifyKind(nonUtcDateTime, DateTimeKind.Utc) | [nonUtcDateTime AT TIME ZONE 'UTC'](https://www.postgresql.org/docs/current/functions-datetime.html#FUNCTIONS-DATETIME-ZONECONVERT) | Added in 6.0, only for timestamp columns +TimeZoneInfo.ConvertTimeBySystemTimeZoneId(utcDateTime, timezone) | [utcDateTime AT TIME ZONE timezone](https://www.postgresql.org/docs/current/functions-datetime.html#FUNCTIONS-DATETIME-ZONECONVERT) | Only for timestamptz columns +TimeZoneInfo.ConvertTimeToUtc(nonUtcDateTime) | [nonUtcDateTime::timestamptz](https://www.postgresql.org/docs/current/functions-datetime.html) | Only for timestamp columns +DateTime.SpecifyKind(utcDateTime, DateTimeKind.Unspecified) | [utcDateTime AT TIME ZONE 'UTC'](https://www.postgresql.org/docs/current/functions-datetime.html#FUNCTIONS-DATETIME-ZONECONVERT) | Only for timestamptz columns +DateTime.SpecifyKind(nonUtcDateTime, DateTimeKind.Utc) | [nonUtcDateTime AT TIME ZONE 'UTC'](https://www.postgresql.org/docs/current/functions-datetime.html#FUNCTIONS-DATETIME-ZONECONVERT) | Only for timestamp columns new DateTime(year, month, day) | [make_date(year, month, day)](https://www.postgresql.org/docs/current/functions-datetime.html) | new DateTime(y, m, d, h, m, s) | [make_timestamp(y, m, d, h, m, s)](https://www.postgresql.org/docs/current/functions-datetime.html) | -new DateTime(y, m, d, h, m, s, kind) | [make_timestamp or make_timestamptz](https://www.postgresql.org/docs/current/functions-datetime.html), based on `kind` | Added in 6.0 -EF.Functions.Sum(timespans) | [sum(timespans)](https://www.postgresql.org/docs/current/functions-aggregate.html#FUNCTIONS-AGGREGATE-TABLE) | Added in 7.0, see [Aggregate functions](#aggregate-functions). -EF.Functions.Average(timespans) | [avg(timespans)](https://www.postgresql.org/docs/current/functions-aggregate.html#FUNCTIONS-AGGREGATE-TABLE) | Added in 7.0, see [Aggregate functions](#aggregate-functions). +new DateTime(y, m, d, h, m, s, kind) | [make_timestamp or make_timestamptz](https://www.postgresql.org/docs/current/functions-datetime.html), based on `kind` | +EF.Functions.Sum(timespans) | [sum(timespans)](https://www.postgresql.org/docs/current/functions-aggregate.html#FUNCTIONS-AGGREGATE-TABLE) | See [Aggregate functions](#aggregate-functions). +EF.Functions.Average(timespans) | [avg(timespans)](https://www.postgresql.org/docs/current/functions-aggregate.html#FUNCTIONS-AGGREGATE-TABLE) | See [Aggregate functions](#aggregate-functions). ## Miscellaneous functions @@ -116,7 +116,8 @@ EF.Functions.Average(timespans) | [avg(timespa ---------------------------------------- | -------------------- collection.Contains(item) | item IN collection enumValue.HasFlag(flag) | enumValue & flag = flag -Guid.NewGuid() | [uuid_generate_v4()](https://www.postgresql.org/docs/current/uuid-ossp.html), or [gen_random_uuid()](https://www.postgresql.org/docs/current/functions-uuid.html) on PostgreSQL 13 with EF Core 5 and above. +Guid.CreateVersion7() | [uuidv7()](https://www.postgresql.org/docs/current/functions-uuid.html) (added in 10 when targeting PG18, client-evaluated otherwise) +Guid.NewGuid() | [gen_random_uuid()](https://www.postgresql.org/docs/current/functions-uuid.html), or [uuid_generate_v4()](https://www.postgresql.org/docs/current/uuid-ossp.html) from [`uuid-ossp`](https://www.postgresql.org/docs/current/uuid-ossp.html) when targeting pre-PG13 nullable.GetValueOrDefault() | coalesce(nullable, 0) nullable.GetValueOrDefault(defaultValue) | coalesce(nullable, defaultValue) @@ -124,10 +125,10 @@ nullable.GetValueOrDefault(defaultValue) | coalesce(nullable, defaultValue) .NET | SQL | Notes ---------------------------- | ------------------------------- | -------- -bytes[i] | get_byte(bytes, i) | Added in 5.0 -bytes.Contains(value) | position(value IN bytes) > 0 | Added in 5.0 -bytes.Length | length(@bytes) | Added in 5.0 -bytes1.SequenceEqual(bytes2) | @bytes = @second | Added in 5.0 +bytes[i] | get_byte(bytes, i) | +bytes.Contains(value) | position(value IN bytes) > 0 | +bytes.Length | length(@bytes) | +bytes1.SequenceEqual(bytes2) | @bytes = @second | ## Math functions @@ -154,7 +155,7 @@ Math.Sign(value) | sign(value)::int | Math.Sqrt(d) | sqrt(d) | Math.Tan(a) | tan(a) | Math.Truncate(d) | trunc(d) | -EF.Functions.Random() | random() | Added in 6.0 +EF.Functions.Random() | random() | See also [Aggregate statistics functions](#aggregate-functions). @@ -162,9 +163,6 @@ See also [Aggregate statistics functions](#aggregate-functions). The following allow expressing [comparisons over SQL row values](https://www.postgresql.org/docs/current/functions-comparisons.html#ROW-WISE-COMPARISON). This are particularly useful for implementing efficient pagination, see [the EF Core docs](https://docs.microsoft.com/ef/core/querying/pagination) for more information. -> [!NOTE] -> All of the below were introduced in version 7.0 of the provider. - .NET | SQL --------------------------------------------------------------------------------- | ---------------- EF.Functions.GreaterThan(ValueTuple.Create(a, b), ValueTuple.Create(c, d)) | (a, b) > (c, d) @@ -176,9 +174,6 @@ ValueTuple.Create(a, b).Equals(ValueTuple.Create(c, d)) ## Network functions -> [!NOTE] -> As of Npgsql 8.0, `IPAddress` and `NpgsqlCidr` are implicitly convertible to `NpgsqlInet`, and so can be used with the functions below which accept `inet`. - .NET | SQL ------------------------------------------------ | --- IPAddress.Parse(string) | [CAST(string AS inet)](https://www.postgresql.org/docs/current/datatype-net-types.html#DATATYPE-INET) @@ -256,9 +251,6 @@ EF.Functions.FuzzyStringMatchDoubleMetaphoneAlt(text) The below translations are for working with label trees from the PostgreSQL [`ltree`](https://www.postgresql.org/docs/current/ltree.html) extension. Use the type to represent ltree and invoke methods on it in EF Core LINQ queries. -> [!NOTE] -> LTree support was introduced in version 6.0 of the provider, and requires PostgreSQL 13 or later. - .NET | SQL ----------------------------------------------------------------- | -------------------- ltree1.IsAncestorOf(ltree2) | ltree1 @> ltree2 @@ -287,9 +279,6 @@ LTree.LongestCommonAncestor(ltree1, ltree2) | lca(index(lt The PostgreSQL aggregate functions are documented [here](https://www.postgresql.org/docs/current/functions-aggregate.html). -> [!NOTE] -> All the below aggregate functions were added in version 7.0. - | .NET | SQL | ---------------------------------------------------------------------------------- | -------------------- | string.Join(", ", agg_strings) | string_agg(agg_strings, ', ') diff --git a/docs/misc/collations-and-case-sensitivity.md b/docs/misc/collations-and-case-sensitivity.md index d2cafdd08f..dfc4508e5a 100644 --- a/docs/misc/collations-and-case-sensitivity.md +++ b/docs/misc/collations-and-case-sensitivity.md @@ -1,18 +1,12 @@ # Collations and Case Sensitivity -> [!NOTE] -> This feature is introduced in EF Core 5.0. -> > It's recommended that you start by reading [the general Entity Framework Core docs on collations and case sensitivity](https://docs.microsoft.com/ef/core/miscellaneous/collations-and-case-sensitivity). -PostgreSQL is a case-sensitive database by default, but provides various possibilities for performing case-insensitive operations and working with collations. Unfortunately, full collation support is recent and somewhat incomplete, so you may need to carefully review your options below and pick the one which suits you. +PostgreSQL is a case-sensitive database by default, but provides various possibilities for performing case-insensitive operations and working with collations. Depending on your PostgreSQL version, full collation support may be somewhat incomplete, so you may need to carefully review your options below and pick the one which suits you. ## PostgreSQL collations -While PostgreSQL has supported collations for a long time, supported was limited to "deterministic" collations, which did not allow for case-insensitive or accent-insensitive operations. PostgreSQL 12 introduced non-deterministic ICU collations, so it is now possible to use collations in a more flexible way. Read more about PostgreSQL collation support [in the documentation](https://www.postgresql.org/docs/current/collation.html). - -> [!NOTE] -> It is not yet possible to use pattern matching operators such as LIKE on columns with a non-deterministic collation. +PostgreSQL has full support for managing collations, and this is the recommended way for managing textual comparisons and sorting. However, note that ; support for non-deterministic collations - coverting case-insensitivity - was relatively limited in some ways. While recent versions such as PostgreSQL 18 support case-insensitive collations quite well, previous versions did not (for example, it was not possible perform pattern matching via LIKE on columns with a non-deterministic collation). Read more about PostgreSQL collation support [in the documentation](https://www.postgresql.org/docs/current/collation.html). ### Creating a collation @@ -64,7 +58,7 @@ All columns created with this configuration will automatically have their collat ## The citext type -The older PostgreSQL method for performing case-insensitive text operations is the `citext` type; it is similar to the `text` type, but operators are functions between `citext` values are implicitly case-insensitive. [The PostgreSQL docs](https://www.postgresql.org/docs/current/citext.html) provide more information on this type. +The older PostgreSQL method for performing case-insensitive text operations is the `citext` type; it is similar to the `text` type, but operators are functions between `citext` values are implicitly case-insensitive. Use this type only if case-insensitive collations (see above) are insufficient for your purposes. [The PostgreSQL docs](https://www.postgresql.org/docs/current/citext.html) provide more information on this type. `citext` is available in a PostgreSQL-bundled extension, so you'll first have to install it: diff --git a/docs/modeling/concurrency.md b/docs/modeling/concurrency.md index fc5a7e8743..afe8dd9ee8 100644 --- a/docs/modeling/concurrency.md +++ b/docs/modeling/concurrency.md @@ -9,7 +9,7 @@ Entity Framework Core supports the concept of optimistic concurrency - a propert Although applications can update concurrency tokens themselves, we frequently rely on the database automatically updating a column on update - a "last modified" timestamp, an SQL Server `rowversion`, etc. Unfortunately PostgreSQL doesn't have such auto-updating columns - but there is one feature that can be used for concurrency token. All PostgreSQL tables have a set of [implicit and hidden system columns](https://www.postgresql.org/docs/current/ddl-system-columns.html), among which `xmin` holds the ID of the latest updating transaction. Since this value automatically gets updated every time the row is changed, it is ideal for use as a concurrency token. -Starting with version 7.0, you can map a `uint` property to the PostgreSQL `xmin` system column using the standard EF Core mechanisms: +You can map a `uint` property to the PostgreSQL `xmin` system column using the standard EF Core mechanisms: ### [Data Annotations](#tab/data-annotations) @@ -46,12 +46,3 @@ public class SomeEntity ``` *** - -In older version of the provider, use the following instead: - -```csharp -protected override void OnModelCreating(ModelBuilder modelBuilder) -{ - modelBuilder.Entity().UseXminAsConcurrencyToken(); -} -``` diff --git a/docs/modeling/generated-properties.md b/docs/modeling/generated-properties.md index e466e9724d..f0c43ad8c0 100644 --- a/docs/modeling/generated-properties.md +++ b/docs/modeling/generated-properties.md @@ -1,8 +1,5 @@ # Value Generation -> [!CAUTION] -> In 3.0.0, the default value generation strategy has changed from the older SERIAL columns to the newer IDENTITY columns. Read the information below carefully if you are migrating an existing database. - > [!NOTE] > It's recommended that you start by reading the general [Entity Framework Core docs on generated properties](https://docs.microsoft.com/en-us/ef/core/modeling/generated-properties). @@ -10,7 +7,7 @@ ### Introduction -Since PostgreSQL 10, the standard way to define auto-incrementing columns is "identity columns". Prior to version 10, "serial columns" were used, which are less SQL-compliant and generally more difficult to manage. For more information on these, [see this blog post](https://blog.2ndquadrant.com/postgresql-10-identity-columns/). Note that since PostgreSQL 10, both support `smallint`, `integer` and `bigint` as their data type. +The standard way to define auto-incrementing columns is "identity columns"; in older versions of PostgreSQL, "serial columns" were used, which are less SQL-compliant and generally more difficult to manage. For more information on these, [see this blog post](https://blog.2ndquadrant.com/postgresql-10-identity-columns/). The Npgsql EF Core provider allows you to choose which of the above you want on a property-by-property basis, or globally on your model. The following "value generation strategies" are available: @@ -106,9 +103,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) } ``` -If you prefer to generate values in the database instead, you can do so by specifying `HasDefaultValueSql` on your property, and call the function to generate the value in the SQL expression. Which function to use depends on your PostgreSQL version: - -### [PG 13+](#tab/13) +If you prefer to generate values in the database instead, you can do so by specifying `HasDefaultValueSql` on your property, and call the function to generate the value in the SQL expression. Starting with PostgreSQL 18, version 7 GUIDs can be generated, which are optimized for database indexes: ```csharp protected override void OnModelCreating(ModelBuilder modelBuilder) @@ -116,19 +111,15 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) modelBuilder .Entity() .Property(e => e.SomeGuidProperty) - .HasDefaultValueSql("gen_random_uuid()"); + .HasDefaultValueSql("uuidv7()"); } ``` -### [Older](#tab/older) - -Versions of PostgreSQL prior to 13 don't include any GUID/UUID generation functions, but extensions such as `uuid-ossp` or `pgcrypto` exist to fill thie gap. This can be done by placing the following code in your model's `OnModelCreating`: +Prior to PostgreSQL 18, you can use an extension such as `pg_uuidv7` to generate version 7 GUIDs, or generate random version 7 GUIDs instead: ```csharp protected override void OnModelCreating(ModelBuilder modelBuilder) { - modelBuilder.HasPostgresExtension("uuid-ossp"); - modelBuilder .Entity() .Property(e => e.SomeGuidProperty) @@ -136,7 +127,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) } ``` -*** +However, note that such version 4 GUIDs perform significantly worse with database indexes. See [the PostgreSQL docs on UUID for more details](https://www.postgresql.org/docs/current/static/datatype-uuid.html). @@ -174,14 +165,9 @@ CREATE TRIGGER "UpdateTimestamp" EXECUTE FUNCTION "Blogs_Update_Timestamp_Function"(); ``` -## Computed Columns - -> [!NOTE] -> This feature works only on PostgreSQL 12 or above. - -PostgreSQL 12 added support for [stored generated columns](https://www.postgresql.org/docs/current/ddl-generated-columns.html), and Npgsql feature supports that feature as well: +## Computed (generated) columns -### [Version 5.0](#tab/efcore5) +EF computed columns - or generated columns, as they're called in PostgreSQL - are fully supported: ```csharp protected override void OnModelCreating(ModelBuilder modelBuilder) @@ -192,23 +178,6 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) } ``` -### [Version 3.x](#tab/efcore3) - -```csharp -protected override void OnModelCreating(ModelBuilder modelBuilder) -{ - modelBuilder.Entity() - .Property(p => p.DisplayName) - .HasComputedColumnSql(@"""FirstName"" || ' ' || ""LastName"""); -} -``` - -*** - -This will cause the following migration SQL to be generated: - -```sql -ALTER TABLE ""Person"" ADD ""DisplayName"" text GENERATED ALWAYS AS (""FirstName"" || ' ' || ""LastName"") STORED; -``` +The above creates a *stored* generated column, meaning that it's computed when a row is inserted or updated, and take up space on disk just like regular columns. PostgreSQL 18 introduced support for *virtual* generated columns, which are instead calculated when read, and take up no space on disk. Virtual generated columns are the default - simply omit `stored: true` above to create them. -Note that this is a *stored* column - it is computed once when the row is updated, and takes space on disk. Virtual computed columns, which are computed on each select, are not yet supported by PostgreSQL. +See the [EF documentation](https://learn.microsoft.com/ef/core/modeling/generated-properties#computed-columns) and the [PostgreSQL documentation](https://www.postgresql.org/docs/current/ddl-generated-columns.html) for more information. diff --git a/docs/modeling/indexes.md b/docs/modeling/indexes.md index 464622a446..817ddad465 100644 --- a/docs/modeling/indexes.md +++ b/docs/modeling/indexes.md @@ -21,9 +21,6 @@ CREATE INDEX "IX_Blog_Id" ON blogs ("Id") INCLUDE ("Name"); ## Treating nulls as non-distinct -> [!NOTE] -> This feature was introduced in version 7.0, and is available starting with PostgreSQL 15. - By default, when you create a unique index, PostgreSQL treats null values as distinct; this means that a unique index can contain multiple null values in a column. When creating an index, you can also instruct PostgreSQL that nulls should be treated as *non-distinct*; this causes a unique constraint violation to be raised if a column contains multiple null values: ```csharp @@ -91,6 +88,3 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) > [!CAUTION] > Do not enable this feature before reading the [PostgreSQL documentation](https://www.postgresql.org/docs/current/sql-createindex.html#SQL-CREATEINDEX-CONCURRENTLY) and understanding the full implications of concurrent index creation. - -> [!NOTE] -> Prior to version 5.0, `IsCreatedConcurrently` erroneously defaulted to `false` - explicitly pass `true` to configure the index for concurrent creation diff --git a/docs/modeling/tables.md b/docs/modeling/tables.md index 61084e0f0b..76a0ef1e12 100644 --- a/docs/modeling/tables.md +++ b/docs/modeling/tables.md @@ -4,7 +4,7 @@ By default, EF Core will map to tables and columns named exactly after your .NET classes and properties, so an entity type named `BlogPost` will be mapped to a PostgreSQL table called `BlogPost`. While there's nothing wrong with that, the PostgreSQL world tends towards snake_case naming instead. In addition, any upper-case letters in unquoted identifiers are automatically converted to lower-case identifiers, so the Npgsql provider generates quotes around all such identifiers. -Starting with 3.0.0, you can use the [EFCore.NamingConventions](https://github.com/efcore/EFCore.NamingConventions) plugin to automatically set all your table and column names to snake_case instead: +The [EFCore.NamingConventions](https://github.com/efcore/EFCore.NamingConventions) plugin to automatically set all your table and column names to snake_case instead: ```csharp protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) @@ -31,6 +31,8 @@ SELECT c.id, c.full_name WHERE c.full_name = 'John Doe'; ``` +However, note that the EFCore.NamingConventions isn't an official part of EF (or of the PostgreSQL provider), and sometimes lags behind in terms of support. + See the [plugin documentation](https://github.com/efcore/EFCore.NamingConventions) for more details, ## Storage parameters diff --git a/docs/release-notes/10.0.md b/docs/release-notes/10.0.md new file mode 100644 index 0000000000..0161e05b21 --- /dev/null +++ b/docs/release-notes/10.0.md @@ -0,0 +1,32 @@ +# 10.0 Release Notes + +Npgsql.EntityFrameworkCore.PostgreSQL version 10.0 is now in development, preview versions are available on [nuget.org](https://www.nuget.org/packages/Npgsql.EntityFrameworkCore.PostgreSQL). + +## Support for PostgreSQL 8 virtual generated columns + +Before PostgreSQL 18, generated (or "computed") columns could only be stored, meaning they were computed when a row is inserted or updated, and take up space on disk just like regular columns. PostgreSQL 18 introduced support for *virtual* generated columns, which are instead calculated when read, and take up no space on disk. Virtual columns can be defined with version 10 of the PostgreSQL provider as follows: + +```c# +protected override void OnModelCreating(ModelBuilder modelBuilder) +{ + modelBuilder.Entity() + .Property(p => p.DisplayName) + .HasComputedColumnSql(@"""FirstName"" || ' ' || ""LastName"""); +} +``` + +Note that previously, `stored: true` had to be specified in the above code sample; starting with version 10, omitting it causes a virtual generated column to be created (supported on PostgreSQL 18 only). + +For more information, [see the documentation](../modeling/generated-properties.md#computed-generated-columns). + +## Other new features + +* When the target PostgreSQL is version is set to 18 (`.UseNpgsql("...", o => o.SetPostgresVersion(18, 0))`), translate [`Guid.CreateVersion7()`](https://learn.microsoft.com/dotnet/api/system.guid.createversion7) to the new [`uuidv7()`](https://www.postgresql.org/docs/18/functions-uuid.html) function. + +See the [10.0.0 milestone](https://github.com/npgsql/efcore.pg/milestone/68?closed=1) for the full list of Npgsql EF provider issues. + +## Breaking changes + +## Contributors + +To be completed. diff --git a/docs/toc.yml b/docs/toc.yml index 86a4377812..fcfc9be732 100644 --- a/docs/toc.yml +++ b/docs/toc.yml @@ -2,6 +2,8 @@ href: index.md - name: Release notes items: + - name: "10.0 (preview)" + href: release-notes/10.0.md - name: "9.0" href: release-notes/9.0.md - name: "8.0" From 348d0a9ebdc111e6d80a7baaf9bdb95f6218e173 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Wed, 9 Jul 2025 10:34:22 +0200 Subject: [PATCH 180/207] Document translations for NodaTime LocalDate.{At,AtMidnight} (#413) See https://github.com/npgsql/efcore.pg/issues/3576 --- docs/mapping/nodatime.md | 39 ++++++++++++++++++------------------ docs/mapping/translations.md | 2 +- docs/release-notes/10.0.md | 1 + 3 files changed, 21 insertions(+), 21 deletions(-) diff --git a/docs/mapping/nodatime.md b/docs/mapping/nodatime.md index f39df92171..070db27606 100644 --- a/docs/mapping/nodatime.md +++ b/docs/mapping/nodatime.md @@ -82,9 +82,6 @@ var oldEvents = context.Events.Where(p => p.SomeDate.Year < 2000); Following is the list of supported NodaTime translations; If an operation you need is missing, please open an issue to request for it. -> [!NOTE] -> Most translations on ZonedDateTime and Period were added in version 6.0 - .NET | SQL | Notes -------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ | ----------- SystemClock.Instance.GetCurrentInstant() | [now()](https://www.postgresql.org/docs/current/functions-datetime.html) | @@ -97,6 +94,8 @@ LocalDateTime.Month (also LocalDate, ZonedDateTime) LocalDateTime.Year (also LocalDate, ZonedDateTime) | [date_part('year', timestamp)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | LocalDateTime.DayOfWeek (also LocalDate, ZonedDateTime) | [floor(date_part('dow', timestamp))::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | LocalDateTime.DayOfYear (also LocalDate, ZonedDateTime) | [date_part('doy', timestamp)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | +LocalDate.AtMidnight() | [date + time](https://www.postgresql.org/docs/current/functions-datetime.html) | Added in 10.0 +LocalDate.At(time) | [date + '00:00:00'](https://www.postgresql.org/docs/current/functions-datetime.html) | Added in 10.0 Period.Seconds (also Duration) | [date_part('second', interval)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | Period.Minutes (also Duration) | [date_part('minute', interval)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | Period.Hours (also Duration) | [date_part('hour', interval)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | @@ -115,22 +114,22 @@ Duration.TotalSeconds Duration.TotalMinutes | [date_part('epoch', interval) / 60.0](https://www.postgresql.org/docs/current/functions-datetime.html) | Duration.TotalDays | [date_part('epoch', interval) / 86400.0](https://www.postgresql.org/docs/current/functions-datetime.html) | Duration.TotalHours | [date_part('epoch', interval) / 3600.0](https://www.postgresql.org/docs/current/functions-datetime.html) | -ZonedDateTime.LocalDateTime | [timestamptz AT TIME ZONE 'UTC'](https://www.postgresql.org/docs/current/functions-datetime.html#FUNCTIONS-DATETIME-ZONECONVERT) | Added in 6.0 -DateInterval.Length | [upper(daterange) - lower(daterange)](https://www.postgresql.org/docs/current/functions-range.html) | Added in 6.0 -DateInterval.Start | [lower(daterange)](https://www.postgresql.org/docs/current/functions-range.html) | Added in 6.0 -DateInterval.End | [upper(daterange) - INTERVAL 'P1D'](https://www.postgresql.org/docs/current/functions-range.html) | Added in 6.0 -DateInterval.Contains(LocalDate) | [daterange @> date](https://www.postgresql.org/docs/current/functions-range.html) | Added in 6.0 -DateInterval.Contains(DateInterval) | [daterange @> daterange](https://www.postgresql.org/docs/current/functions-range.html) | Added in 6.0 -DateInterval.Intersection(DateInterval) | [daterange * daterange](https://www.postgresql.org/docs/current/functions-range.html) | Added in 6.0 -DateInterval.Union(DateInterval) | [daterange + daterange](https://www.postgresql.org/docs/current/functions-range.html) | Added in 6.0 -Instant.InZone(DateTimeZoneProviders.Tzdb["Europe/Berlin"]).LocalDateTime | [timestamptz AT TIME ZONE 'Europe/Berlin'](https://www.postgresql.org/docs/current/functions-datetime.html#FUNCTIONS-DATETIME-ZONECONVERT) | Added in 6.0 -LocalDateTime.InZoneLeniently(DateTimeZoneProviders.Tzdb["Europe/Berlin"]).ToInstant() | [timestamp AT TIME ZONE 'Europe/Berlin'](https://www.postgresql.org/docs/current/functions-datetime.html#FUNCTIONS-DATETIME-ZONECONVERT) | Added in 6.0 -ZonedDateTime.ToInstant | No PG operation (.NET-side conversion from ZonedDateTime to Instant only) | Added in 6.0 -Instant.InUtc | No PG operation (.NET-side conversion from Instant to ZonedDateTime only) | Added in 6.0 -Instant.ToDateTimeUtc | No PG operation (.NET-side conversion from Instant to UTC DateTime only) | Added in 6.0 -EF.Functions.Sum(periods) | [sum(periods)](https://www.postgresql.org/docs/current/functions-aggregate.html#FUNCTIONS-AGGREGATE-TABLE) | Added in 7.0, see [Aggregate functions](translations.md#aggregate-functions). -EF.Functions.Sum(durations) | [sum(durations)](https://www.postgresql.org/docs/current/functions-aggregate.html#FUNCTIONS-AGGREGATE-TABLE) | Added in 7.0, see [Aggregate functions](translations.md#aggregate-functions). -EF.Functions.Average(periods) | [avg(durations)](https://www.postgresql.org/docs/current/functions-aggregate.html#FUNCTIONS-AGGREGATE-TABLE) | Added in 7.0, see [Aggregate functions](translations.md#aggregate-functions). -EF.Functions.Average(durations) | [avg(durations)](https://www.postgresql.org/docs/current/functions-aggregate.html#FUNCTIONS-AGGREGATE-TABLE) | Added in 7.0, see [Aggregate functions](translations.md#aggregate-functions). +ZonedDateTime.LocalDateTime | [timestamptz AT TIME ZONE 'UTC'](https://www.postgresql.org/docs/current/functions-datetime.html#FUNCTIONS-DATETIME-ZONECONVERT) | +DateInterval.Length | [upper(daterange) - lower(daterange)](https://www.postgresql.org/docs/current/functions-range.html) | +DateInterval.Start | [lower(daterange)](https://www.postgresql.org/docs/current/functions-range.html) | +DateInterval.End | [upper(daterange) - INTERVAL 'P1D'](https://www.postgresql.org/docs/current/functions-range.html) | +DateInterval.Contains(LocalDate) | [daterange @> date](https://www.postgresql.org/docs/current/functions-range.html) | +DateInterval.Contains(DateInterval) | [daterange @> daterange](https://www.postgresql.org/docs/current/functions-range.html) | +DateInterval.Intersection(DateInterval) | [daterange * daterange](https://www.postgresql.org/docs/current/functions-range.html) | +DateInterval.Union(DateInterval) | [daterange + daterange](https://www.postgresql.org/docs/current/functions-range.html) | +Instant.InZone(DateTimeZoneProviders.Tzdb["Europe/Berlin"]).LocalDateTime | [timestamptz AT TIME ZONE 'Europe/Berlin'](https://www.postgresql.org/docs/current/functions-datetime.html#FUNCTIONS-DATETIME-ZONECONVERT) | +LocalDateTime.InZoneLeniently(DateTimeZoneProviders.Tzdb["Europe/Berlin"]).ToInstant() | [timestamp AT TIME ZONE 'Europe/Berlin'](https://www.postgresql.org/docs/current/functions-datetime.html#FUNCTIONS-DATETIME-ZONECONVERT) | +ZonedDateTime.ToInstant | No PG operation (.NET-side conversion from ZonedDateTime to Instant only) | +Instant.InUtc | No PG operation (.NET-side conversion from Instant to ZonedDateTime only) | +Instant.ToDateTimeUtc | No PG operation (.NET-side conversion from Instant to UTC DateTime only) | +EF.Functions.Sum(periods) | [sum(periods)](https://www.postgresql.org/docs/current/functions-aggregate.html#FUNCTIONS-AGGREGATE-TABLE) | See [Aggregate functions](translations.md#aggregate-functions). +EF.Functions.Sum(durations) | [sum(durations)](https://www.postgresql.org/docs/current/functions-aggregate.html#FUNCTIONS-AGGREGATE-TABLE) | See [Aggregate functions](translations.md#aggregate-functions). +EF.Functions.Average(periods) | [avg(durations)](https://www.postgresql.org/docs/current/functions-aggregate.html#FUNCTIONS-AGGREGATE-TABLE) | See [Aggregate functions](translations.md#aggregate-functions). +EF.Functions.Average(durations) | [avg(durations)](https://www.postgresql.org/docs/current/functions-aggregate.html#FUNCTIONS-AGGREGATE-TABLE) | See [Aggregate functions](translations.md#aggregate-functions). In addition to the above, most arithmetic operators are also translated (e.g. LocalDate + Period). diff --git a/docs/mapping/translations.md b/docs/mapping/translations.md index c1e5248616..8ad7f2bd1c 100644 --- a/docs/mapping/translations.md +++ b/docs/mapping/translations.md @@ -53,7 +53,7 @@ EF.Functions.StringToArray(s, "\|", "FOO") | [string_agg(s, ' > [!NOTE] > Some of the operations below depend on the concept of a "local time zone" (e.g. `DateTime.Today`). While in .NET this is the machine time zone where .NET is running, the corresponding PostgreSQL translations use the [`TimeZone`](https://www.postgresql.org/docs/current/runtime-config-client.html#GUC-TIMEZONE) connection parameter as the local time zone. > -> Since version 6.0, many of the below DateTime translations are also supported on DateTimeOffset. +> Many of the below DateTime translations are also supported on `DateTimeOffset`. > > See also Npgsql's [NodaTime support](/efcore/mapping/nodatime.html), which is a better and safer way of interacting with date/time data. diff --git a/docs/release-notes/10.0.md b/docs/release-notes/10.0.md index 0161e05b21..34797641db 100644 --- a/docs/release-notes/10.0.md +++ b/docs/release-notes/10.0.md @@ -22,6 +22,7 @@ For more information, [see the documentation](../modeling/generated-properties.m ## Other new features * When the target PostgreSQL is version is set to 18 (`.UseNpgsql("...", o => o.SetPostgresVersion(18, 0))`), translate [`Guid.CreateVersion7()`](https://learn.microsoft.com/dotnet/api/system.guid.createversion7) to the new [`uuidv7()`](https://www.postgresql.org/docs/18/functions-uuid.html) function. +* NodaTime `LocalDate.At()` and `LocalDate.AtMidnight()` are now translated. See the [10.0.0 milestone](https://github.com/npgsql/efcore.pg/milestone/68?closed=1) for the full list of Npgsql EF provider issues. From e8411130dfec16a9e2b4c675c9d30597c8ec7cdb Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Wed, 9 Jul 2025 11:03:34 +0200 Subject: [PATCH 181/207] Fixup --- docs/mapping/nodatime.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/mapping/nodatime.md b/docs/mapping/nodatime.md index 070db27606..ff31884dd9 100644 --- a/docs/mapping/nodatime.md +++ b/docs/mapping/nodatime.md @@ -94,8 +94,8 @@ LocalDateTime.Month (also LocalDate, ZonedDateTime) LocalDateTime.Year (also LocalDate, ZonedDateTime) | [date_part('year', timestamp)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | LocalDateTime.DayOfWeek (also LocalDate, ZonedDateTime) | [floor(date_part('dow', timestamp))::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | LocalDateTime.DayOfYear (also LocalDate, ZonedDateTime) | [date_part('doy', timestamp)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | -LocalDate.AtMidnight() | [date + time](https://www.postgresql.org/docs/current/functions-datetime.html) | Added in 10.0 -LocalDate.At(time) | [date + '00:00:00'](https://www.postgresql.org/docs/current/functions-datetime.html) | Added in 10.0 +LocalDate.At(time) | [date + time](https://www.postgresql.org/docs/current/functions-datetime.html) | Added in 10.0 +LocalDate.AtMidnight() | [date + '00:00:00'](https://www.postgresql.org/docs/current/functions-datetime.html) | Added in 10.0 Period.Seconds (also Duration) | [date_part('second', interval)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | Period.Minutes (also Duration) | [date_part('minute', interval)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | Period.Hours (also Duration) | [date_part('hour', interval)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | From d663a0cb6506a723f28c52c25eee758414ff043e Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Wed, 1 Oct 2025 16:07:38 +0200 Subject: [PATCH 182/207] Release notes and tweaks around EFCore.PG support for JSON (#420) --- docs/mapping/json.md | 24 ++++++-- docs/release-notes/10.0.md | 118 ++++++++++++++++++++++++++++++++++++- docs/toc.yml | 2 +- 3 files changed, 137 insertions(+), 7 deletions(-) diff --git a/docs/mapping/json.md b/docs/mapping/json.md index 0444da082e..3393eeb16e 100644 --- a/docs/mapping/json.md +++ b/docs/mapping/json.md @@ -57,13 +57,13 @@ With string mapping, the EF Core provider will save and load properties to datab If your column JSON contains documents with a stable schema, you can map them to your own .NET types (or POCOs); EF will use System.Text.Json APIs under the hood to serialize instances of your types to JSON documents before sending them to the database, and to deserialize documents coming back from the database. This effectively allows mapping an arbitrary .NET type - or object graph - to a single column in the database. -EF 7.0 introduced the "JSON Columns" feature, which maps a database JSON column via EF's "owned entity" mapping concept, using `ToJson()`. In this approach, EF fully models the types within the JSON document - just like it models regular tables and columns - and uses that information to perform better queries and updates. Full support for ToJson has been added to version 8.0 of the Npgsql EF provider. +As of EF 10, the recommended way to map .NET types to JSON in the database is via complex types ([see EF release notes](https://learn.microsoft.com/en-us/ef/core/what-is-new/ef-core-10.0/whatsnew#json)). In this mode, EF is fully aware of the structure of your JSON document - just like it's aware of your tables and columns - and provides powerful, rich querying and updating capabilities. Prior to EF 10, similar modeling was available via the "owned entity" concept, but this modeling created several issues ([see here for more details](https://learn.microsoft.com/en-us/ef/core/what-is-new/ef-core-10.0/whatsnew#json)). If you're using EF 10 or above, complex types are the recommended way to map .NET types. -As an alternative, prior to version 8.0, the Npgsql EF provider has supported JSON POCO mapping by simply delegating serialization/deserialization to System.Text.Json; in this model, EF itself model the contents of the JSON document, and cannot take that structure into account for queries and updates. This approach can now be considered deprecated as it allows for less powerful mapping and supports less query types; using ToJson() is now the recommended way to map POCOs to JSON. +As an 3rd alternative, prior to version 8.0, the Npgsql EF provider has supported JSON POCO mapping by simply delegating serialization/deserialization to System.Text.Json; in this mode, EF itself is oblivious to the contents of the JSON document, and cannot take that structure into account for queries and updates. This approach can now be considered deprecated as it allows for less powerful mapping and supports less query types; using complex types with `ToJson()` is now the recommended way to map POCOs to JSON. -### ToJson (owned entity mapping) +### EF modeling with ToJson (recommended) -Npgsql's support for `ToJson()` is fully aligned with the general EF support; see the [EF documentation for more information](https://learn.microsoft.com/ef/core/what-is-new/ef-core-7.0/whatsnew#json-columns). +Npgsql's support for `ToJson()` is fully aligned with the general EF support; see the [EF documentation for more information](https://learn.microsoft.com/ef/core/what-is-new/ef-core-10.0/whatsnew#json). To get you started quickly, assume that we have the following Customer type, with a Details property that we want to map to a single JSON column in the database: @@ -90,6 +90,18 @@ public class Order // Part of the JSON column To instruct EF to map CustomerDetails - and within it, Order - to a JSON column, configure it as follows: +#### [Complex types (EF10+)](#tab/complex-types) + +```csharp +protected override void OnModelCreating(ModelBuilder modelBuilder) +{ + modelBuilder.Entity() + .ComplexProperty(c => c.Details, d => d.ToJson()); +} +``` + +#### [Owned entities](#tab/owned entities) + ```csharp protected override void OnModelCreating(ModelBuilder modelBuilder) { @@ -102,6 +114,8 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) } ``` +*** + At this point you can interact with the Customer just like you would normally, and EF will seamlessly serialize and deserialize it to a JSON column in the database. You can also perform LINQ queries which reference properties inside the JSON document, and these will get translated to SQL. ### Legacy POCO mapping (deprecated) @@ -134,7 +148,7 @@ public class Order // Part of the JSON column } ``` -### [Fluent API](#tab/fluent-api) +#### [Fluent API](#tab/fluent-api) ```csharp class MyContext : DbContext diff --git a/docs/release-notes/10.0.md b/docs/release-notes/10.0.md index 34797641db..566060c6c3 100644 --- a/docs/release-notes/10.0.md +++ b/docs/release-notes/10.0.md @@ -2,6 +2,119 @@ Npgsql.EntityFrameworkCore.PostgreSQL version 10.0 is now in development, preview versions are available on [nuget.org](https://www.nuget.org/packages/Npgsql.EntityFrameworkCore.PostgreSQL). +## Full support for EF 10 JSON complex types + +EF 10 introduced support for mapping .NET types as JSON complex types, resolving several issues that existed with the previous JSON mapping via owned entities ([see release notes for more information](https://learn.microsoft.com/en-us/ef/core/what-is-new/ef-core-10.0/whatsnew#json)). The PG provider providers full support for this feature full support for this as well: + +```c# +modelBuilder.Entity(b => +{ + b.ComplexProperty(c => c.ShippingAddress, c => c.ToJson()); + b.ComplexProperty(c => c.BillingAddress, c => c.ToJson()); +}); +``` + +This configuration causes the following table to be created for your customers: + +```sql +CREATE TABLE "Customers" ( + "Id" integer GENERATED BY DEFAULT AS IDENTITY, + "Name" text, + "BillingAddress" jsonb NOT NULL, + "ShippingAddress" jsonb NOT NULL, + CONSTRAINT "PK_Customers" PRIMARY KEY ("Id") +); +``` + +This is now the preferred way to perform strongly-typed JSON mapping of arbitrary .NET types, and replaces owned entities and [legacy POCO mapping](../mapping/json.md?#legacy-poco-mapping-deprecated). + +The provider now also supports performing partial updates within JSON documents using `ExecuteUpdate`. For example, the following efficiently copies overwrites all Customers' shipping address streets with their billing address streets: + +```c# +await context.Customers.ExecuteUpdateAsync(s => + s.SetProperty(b => b.ShippingAddress.Street, b => b.BillingAddress.Street)); +``` + +This produces the following SQL: + +```sql +UPDATE "Customers" AS c +SET "ShippingAddress" = jsonb_set(c."ShippingAddress", '{Street}', c."BillingAddress" -> 'Street') +``` + +## Better support for JSON scalar (primitive) collections + +In most relational databases, scalar collections are mapped to a JSON column, the the collection is serialized to a JSON array in the database. PostgreSQL, however, is unique in providing a 1st-class array type, so the EF provider maps scalar collections to array instead. For example, given the following type: + +```c# +public class Customer +{ + public int Id { get; set; } + public string[] Tags { get; set; } +} +``` + +... the PostgreSQL provider will create the following table (note that `text[]` array column): + +```sql +CREATE TABLE "Customers" ( + "Id" integer GENERATED BY DEFAULT AS IDENTITY, + "Tags" text[] NOT NULL, + CONSTRAINT "PK_Customers" PRIMARY KEY ("Id") +); +``` + +However, when scalar collections are nested within a JSON document, they must be mapped to JSON arrays, as in other databases: + +```c# +public class Customer +{ + public int Id { get; set; } + public Address Address { get; set; } +} + +public class Address +{ + // ... + + public string[] Tags { get; set; } +} +``` + +Version 10 of the provider now produces much better SQL when querying such nested scalar collections. For example, when querying using Contains: + +```c# +var customers = await context.Customers.Where(b => b.ShippingAddress.Tags.Contains("foo")).ToListAsync(); +``` + +... previous versions of the provider generated the following complicated (and inefficient) SQL: + +```sql +SELECT c."Id", c."Name", c."ShippingAddress" +FROM "Customers" AS c +WHERE 'foo' = ANY ((ARRAY(SELECT CAST(element AS text) FROM jsonb_array_elements_text(c."ShippingAddress" -> 'Tags') WITH ORDINALITY AS t(element) ORDER BY ordinality))) +``` + +Version 10, in contrast, produces the following cleaner SQL, which can also benefit from indexes: + +```sql +SELECT c."Id", c."Name", c."ShippingAddress" +FROM "Customers" AS c +WHERE (c."ShippingAddress" -> 'Tags') @> to_jsonb('foo'::text) +``` + +Finally, version 10 of the provider also allows you to map a non-nested scalar collection to a JSON column, instead of to an array column, and provides fully querying capabilities: + +```c# +public class Customer +{ + // ... + + [Column(TypeName = "jsonb")] + public string[] Tags { get; set; } +} +``` + ## Support for PostgreSQL 8 virtual generated columns Before PostgreSQL 18, generated (or "computed") columns could only be stored, meaning they were computed when a row is inserted or updated, and take up space on disk just like regular columns. PostgreSQL 18 introduced support for *virtual* generated columns, which are instead calculated when read, and take up no space on disk. Virtual columns can be defined with version 10 of the PostgreSQL provider as follows: @@ -19,9 +132,12 @@ Note that previously, `stored: true` had to be specified in the above code sampl For more information, [see the documentation](../modeling/generated-properties.md#computed-generated-columns). +## Support for UUIDv7 + +By default, EF generates GUID (or UUID) values locally in .NET, rather than relying on the database to generate them. Version 9 of the PG provider already switched to generating UUIDv7 values by default ([see release note](9.0.md#uuidv7-guids-are-generated-by-default)), which are significantly better for database indexes. PostgreSQL 18 also added the [`uuidv7()`](https://www.postgresql.org/docs/18/functions-uuid.html#FUNC_UUID_GEN_TABLE) built-in function, which allows database generation of UUIDv7 values. In EFCore.PG 10, if you configure the provider to target PG 18 (`.UseNpgsql("...", o => o.SetPostgresVersion(18, 0))`), the provider will also translate [`Guid.CreateVersion7()`](https://learn.microsoft.com/dotnet/api/system.guid.createversion7) to that function. + ## Other new features -* When the target PostgreSQL is version is set to 18 (`.UseNpgsql("...", o => o.SetPostgresVersion(18, 0))`), translate [`Guid.CreateVersion7()`](https://learn.microsoft.com/dotnet/api/system.guid.createversion7) to the new [`uuidv7()`](https://www.postgresql.org/docs/18/functions-uuid.html) function. * NodaTime `LocalDate.At()` and `LocalDate.AtMidnight()` are now translated. See the [10.0.0 milestone](https://github.com/npgsql/efcore.pg/milestone/68?closed=1) for the full list of Npgsql EF provider issues. diff --git a/docs/toc.yml b/docs/toc.yml index fcfc9be732..c03efd2186 100644 --- a/docs/toc.yml +++ b/docs/toc.yml @@ -2,7 +2,7 @@ href: index.md - name: Release notes items: - - name: "10.0 (preview)" + - name: "10.0 (rc)" href: release-notes/10.0.md - name: "9.0" href: release-notes/9.0.md From 78261dd9bf0493a8e887c0dbda40d52d91355a22 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Sun, 5 Oct 2025 23:15:33 +0200 Subject: [PATCH 183/207] Breaking change notes related to cidr (#421) See https://github.com/npgsql/npgsql/issues/5891 See https://github.com/npgsql/efcore.pg/issues/3321 --- docs/release-notes/10.0.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/release-notes/10.0.md b/docs/release-notes/10.0.md index 566060c6c3..133c75e98e 100644 --- a/docs/release-notes/10.0.md +++ b/docs/release-notes/10.0.md @@ -144,6 +144,8 @@ See the [10.0.0 milestone](https://github.com/npgsql/efcore.pg/milestone/68?clos ## Breaking changes +* `EF.Functions.Network()` and `EF.Functions.Merge()` have been changed to return the new .NET [`IPNetwork`](https://learn.microsoft.com/dotnet/api/system.net.ipnetwork) instead of the obsolete `NpgsqlCidr`. The new `IPNetwork` type works with all other functions as well (but no breaking changes were necessary). + ## Contributors To be completed. From bd2e50e39489fec6bf02162965a55cbcf7896f48 Mon Sep 17 00:00:00 2001 From: Amrit Date: Mon, 6 Oct 2025 02:11:23 -0400 Subject: [PATCH 184/207] Fix Typo (#422) --- docs/release-notes/10.0.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/release-notes/10.0.md b/docs/release-notes/10.0.md index 133c75e98e..e8ea3ff2d6 100644 --- a/docs/release-notes/10.0.md +++ b/docs/release-notes/10.0.md @@ -115,7 +115,7 @@ public class Customer } ``` -## Support for PostgreSQL 8 virtual generated columns +## Support for PostgreSQL 18 virtual generated columns Before PostgreSQL 18, generated (or "computed") columns could only be stored, meaning they were computed when a row is inserted or updated, and take up space on disk just like regular columns. PostgreSQL 18 introduced support for *virtual* generated columns, which are instead calculated when read, and take up no space on disk. Virtual columns can be defined with version 10 of the PostgreSQL provider as follows: From a65e7704b08b40d53ca5effc4f496c0f88262eea Mon Sep 17 00:00:00 2001 From: Ryan Spain <8723433+ryanspain@users.noreply.github.com> Date: Thu, 16 Oct 2025 19:05:36 +0100 Subject: [PATCH 185/207] Fix tab heading link for owned entities section (#423) --- docs/mapping/json.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/mapping/json.md b/docs/mapping/json.md index 3393eeb16e..462e70714a 100644 --- a/docs/mapping/json.md +++ b/docs/mapping/json.md @@ -100,7 +100,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) } ``` -#### [Owned entities](#tab/owned entities) +#### [Owned entities](#tab/owned-entities) ```csharp protected override void OnModelCreating(ModelBuilder modelBuilder) From 1fa31f5642f9d506979f391bb47360c2d351f97d Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Fri, 24 Oct 2025 13:18:29 +0200 Subject: [PATCH 186/207] Work on Npgsql 10 breaking change notes (#425) --- docs/release-notes/10.0.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/release-notes/10.0.md b/docs/release-notes/10.0.md index e8ea3ff2d6..244264622f 100644 --- a/docs/release-notes/10.0.md +++ b/docs/release-notes/10.0.md @@ -145,6 +145,7 @@ See the [10.0.0 milestone](https://github.com/npgsql/efcore.pg/milestone/68?clos ## Breaking changes * `EF.Functions.Network()` and `EF.Functions.Merge()` have been changed to return the new .NET [`IPNetwork`](https://learn.microsoft.com/dotnet/api/system.net.ipnetwork) instead of the obsolete `NpgsqlCidr`. The new `IPNetwork` type works with all other functions as well (but no breaking changes were necessary). +* The PostgreSQL network type `cidr` is now scaffolded to the new .NET [`IPNetwork`](https://learn.microsoft.com/dotnet/api/system.net.ipnetwork) type. The older Npgsql representation for `cidr` - the `NpgsqlCidr` type - has been obsoleted and will be removed in a future release. ## Contributors From 8ad7a1cb49cc1061f1b6a6bfd94981b61b534792 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Wed, 19 Nov 2025 07:22:04 +0100 Subject: [PATCH 187/207] Cube docs --- docs/release-notes/10.0.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/docs/release-notes/10.0.md b/docs/release-notes/10.0.md index 244264622f..a0a1c48fce 100644 --- a/docs/release-notes/10.0.md +++ b/docs/release-notes/10.0.md @@ -136,6 +136,21 @@ For more information, [see the documentation](../modeling/generated-properties.m By default, EF generates GUID (or UUID) values locally in .NET, rather than relying on the database to generate them. Version 9 of the PG provider already switched to generating UUIDv7 values by default ([see release note](9.0.md#uuidv7-guids-are-generated-by-default)), which are significantly better for database indexes. PostgreSQL 18 also added the [`uuidv7()`](https://www.postgresql.org/docs/18/functions-uuid.html#FUNC_UUID_GEN_TABLE) built-in function, which allows database generation of UUIDv7 values. In EFCore.PG 10, if you configure the provider to target PG 18 (`.UseNpgsql("...", o => o.SetPostgresVersion(18, 0))`), the provider will also translate [`Guid.CreateVersion7()`](https://learn.microsoft.com/dotnet/api/system.guid.createversion7) to that function. +## Support for the cube extension + +PostgreSQL bundles the [`cube`](https://www.postgresql.org/docs/current/cube.html) extension, which provides a multi-dimensional cube data type and associated operations. EFCore.PG 10 now fully supports the `cube` type out-of-the-box, simply add an `NpgsqlCube` property to your entity type: + +```c# +public class Blog +{ + ... + + public NpgsqlCube Cube { get; set; } +} +``` + +Most translations over the type are supported as well. Thanks to [@kirkbrauer](https://github.com/kirkbrauer) for contributing this feature! + ## Other new features * NodaTime `LocalDate.At()` and `LocalDate.AtMidnight()` are now translated. From fe363f9470074bd1a8a9ba5f90c242ae9521547d Mon Sep 17 00:00:00 2001 From: Kirk Brauer Date: Sat, 22 Nov 2025 04:10:24 -0500 Subject: [PATCH 188/207] Add cube translation functions (#431) --- docs/mapping/translations.md | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/docs/mapping/translations.md b/docs/mapping/translations.md index 8ad7f2bd1c..d9433e5b68 100644 --- a/docs/mapping/translations.md +++ b/docs/mapping/translations.md @@ -275,6 +275,29 @@ ltree.Index(subpath) | index(ltree, ltree.Index(subpath, 2) | index(ltree, subpath, 2) LTree.LongestCommonAncestor(ltree1, ltree2) | lca(index(ltree1, ltree2) +## Cube functions + +The below translations are for working with cubes from the PostgreSQL [`cube`](https://www.postgresql.org/docs/current/cube.html) extension. Use the type to represent cube and invoke methods on it in EF Core LINQ queries. + +.NET | SQL +----------------------------------- | -------------------- +cube1.Overlaps(cube2) | [cube1 && cube2](https://www.postgresql.org/docs/current/cube.html#CUBE-OPERATORS-TABLE) +cube1.Contains(cube2) | [cube1 @> cube2](https://www.postgresql.org/docs/current/cube.html#CUBE-OPERATORS-TABLE) +cube1.ContainedBy(cube2) | [cube1 <@ cube2](https://www.postgresql.org/docs/current/cube.html#CUBE-OPERATORS-TABLE) +cube.NthCoordinate(n) | [cube -> n + 1](https://www.postgresql.org/docs/current/cube.html#CUBE-OPERATORS-TABLE) +cube.NthCoordinateKnn(n) | [cube ~> n + 1](https://www.postgresql.org/docs/current/cube.html#CUBE-OPERATORS-TABLE) +cube1.Distance(cube2) | [cube1 <-> cube2](https://www.postgresql.org/docs/current/cube.html#CUBE-OPERATORS-TABLE) +cube1.DistanceTaxicab(cube2) | [cube1 <#> cube2](https://www.postgresql.org/docs/current/cube.html#CUBE-OPERATORS-TABLE) +cube1.DistanceChebyshev(cube2) | [cube1 <=> cube2](https://www.postgresql.org/docs/current/cube.html#CUBE-OPERATORS-TABLE) +cube1.Union(cube2) | [cube_union(cube1, cube2)](https://www.postgresql.org/docs/current/cube.html#CUBE-FUNCTIONS-TABLE) +cube1.Intersect(cube2) | [cube_inter(cube1, cube2)](https://www.postgresql.org/docs/current/cube.html#CUBE-FUNCTIONS-TABLE) +cube.Enlarge(r, n) | [cube_enlarge(cube, r, n)](https://www.postgresql.org/docs/current/cube.html#CUBE-FUNCTIONS-TABLE) +cube.Dimensions | [cube_dim(cube)](https://www.postgresql.org/docs/current/cube.html#CUBE-FUNCTIONS-TABLE) +cube.IsPoint | [cube_is_point(cube)](https://www.postgresql.org/docs/current/cube.html#CUBE-FUNCTIONS-TABLE) +cube.ToSubset(indexes) | [cube_subset(cube, indexes + 1)](https://www.postgresql.org/docs/current/cube.html#CUBE-FUNCTIONS-TABLE) +cube.LowerLeft[n] | [cube_ll_coord(cube, n + 1)](https://www.postgresql.org/docs/current/cube.html#CUBE-FUNCTIONS-TABLE) +cube.UpperRight[n] | [cube_ur_coord(cube, n + 1)](https://www.postgresql.org/docs/current/cube.html#CUBE-FUNCTIONS-TABLE) + ## Aggregate functions The PostgreSQL aggregate functions are documented [here](https://www.postgresql.org/docs/current/functions-aggregate.html). From 37a290d16895e854cec6cc23c210e316c1d71370 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Sat, 22 Nov 2025 19:04:03 +0100 Subject: [PATCH 189/207] Some more Npgsql 10 release note tweaks (#433) --- docs/release-notes/10.0.md | 4 ---- 1 file changed, 4 deletions(-) diff --git a/docs/release-notes/10.0.md b/docs/release-notes/10.0.md index a0a1c48fce..7804dc2596 100644 --- a/docs/release-notes/10.0.md +++ b/docs/release-notes/10.0.md @@ -161,7 +161,3 @@ See the [10.0.0 milestone](https://github.com/npgsql/efcore.pg/milestone/68?clos * `EF.Functions.Network()` and `EF.Functions.Merge()` have been changed to return the new .NET [`IPNetwork`](https://learn.microsoft.com/dotnet/api/system.net.ipnetwork) instead of the obsolete `NpgsqlCidr`. The new `IPNetwork` type works with all other functions as well (but no breaking changes were necessary). * The PostgreSQL network type `cidr` is now scaffolded to the new .NET [`IPNetwork`](https://learn.microsoft.com/dotnet/api/system.net.ipnetwork) type. The older Npgsql representation for `cidr` - the `NpgsqlCidr` type - has been obsoleted and will be removed in a future release. - -## Contributors - -To be completed. From fa97565e908b62a54e86ffe7b60dc2f96bd28765 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Fri, 2 Jan 2026 14:41:46 +0100 Subject: [PATCH 190/207] Document EFCore.PG 10 as released (#441) --- docs/release-notes/10.0.md | 2 +- docs/toc.yml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/release-notes/10.0.md b/docs/release-notes/10.0.md index 7804dc2596..b57db74bc4 100644 --- a/docs/release-notes/10.0.md +++ b/docs/release-notes/10.0.md @@ -1,6 +1,6 @@ # 10.0 Release Notes -Npgsql.EntityFrameworkCore.PostgreSQL version 10.0 is now in development, preview versions are available on [nuget.org](https://www.nuget.org/packages/Npgsql.EntityFrameworkCore.PostgreSQL). +Npgsql.EntityFrameworkCore.PostgreSQL version 10.0 is out and available on [nuget.org](https://www.nuget.org/packages/Npgsql.EntityFrameworkCore.PostgreSQL). ## Full support for EF 10 JSON complex types diff --git a/docs/toc.yml b/docs/toc.yml index c03efd2186..0e71fa8271 100644 --- a/docs/toc.yml +++ b/docs/toc.yml @@ -2,7 +2,7 @@ href: index.md - name: Release notes items: - - name: "10.0 (rc)" + - name: "10.0" href: release-notes/10.0.md - name: "9.0" href: release-notes/9.0.md From bae92b9a217ae77bc2947907a95f1caa2c666be1 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Sat, 24 Jan 2026 10:53:36 +0100 Subject: [PATCH 191/207] Document temporal constraints (#444) See https://github.com/npgsql/efcore.pg/issues/2097 --- docs/misc/temporal-constraints.md | 167 ++++++++++++++++++++++++++++++ docs/release-notes/11.0.md | 88 ++++++++++++++++ docs/toc.yml | 4 + 3 files changed, 259 insertions(+) create mode 100644 docs/misc/temporal-constraints.md create mode 100644 docs/release-notes/11.0.md diff --git a/docs/misc/temporal-constraints.md b/docs/misc/temporal-constraints.md new file mode 100644 index 0000000000..c817296437 --- /dev/null +++ b/docs/misc/temporal-constraints.md @@ -0,0 +1,167 @@ +# Temporal constraints + +> [!NOTE] +> Temporal constraints are only supported starting with version 11 of the EF provider, and require PostgreSQL 18. + +PostgreSQL 18 introduced temporal constraints, which allow you to enforce data integrity rules over time periods. These features are particularly valuable for applications that need to track the validity periods of data, such as employee records, pricing information, equipment assignments, or any scenario where you need to maintain a complete historical timeline without gaps or overlaps. + +Temporal constraints work with PostgreSQL's range types, such as `daterange`, `tstzrange` (timestamp with timezone range), and `tsrange` (timestamp range). + +## WITHOUT OVERLAPS + +The `WITHOUT OVERLAPS` clause can be added to primary and alternate keys to ensure that for any given set of scalar column values, the associated time ranges do not overlap. + +A temporal key combines regular columns with a range column. This allows multiple rows for the same entity (e.g., same employee ID) as long as their time periods don't overlap, enabling you to maintain a complete history of changes: + +```csharp +public class Employee +{ + public int EmployeeId { get; set; } + public string Name { get; set; } + public string Department { get; set; } + public decimal Salary { get; set; } + public NpgsqlRange ValidPeriod { get; set; } +} + +protected override void OnModelCreating(ModelBuilder modelBuilder) +{ + modelBuilder.Entity(b => + { + // Configure the range property with a default value + b.Property(e => e.ValidPeriod) + .HasDefaultValueSql("tstzrange(now(), 'infinity', '[)')"); + + // Configure the temporal primary key + b.HasKey(e => new { e.EmployeeId, e.ValidPeriod }) + .HasWithoutOverlaps(); + }); +} +``` + +This configuration creates the following table: + +```sql +CREATE TABLE employees ( + employee_id INTEGER, + name VARCHAR(100) NOT NULL, + department VARCHAR(50) NOT NULL, + salary DECIMAL(10,2) NOT NULL, + valid_period tstzrange NOT NULL DEFAULT tstzrange(now(), 'infinity', '[)'), + PRIMARY KEY (employee_id, valid_period WITHOUT OVERLAPS) +); +``` + +With this constraint, you can insert multiple records for the same employee as long as their time periods don't overlap: + +```sql +-- Valid: Two records for the same employee with non-overlapping periods +INSERT INTO employees (employee_id, name, department, salary, valid_period) +VALUES + (1, 'Alice Johnson', 'Engineering', 75000, tstzrange('2024-01-01', '2025-01-01', '[)')), + (1, 'Alice Johnson', 'Engineering', 85000, tstzrange('2025-01-01', 'infinity', '[)')); + +-- Invalid: This would fail because it overlaps with existing data +INSERT INTO employees (employee_id, name, department, salary, valid_period) +VALUES (1, 'Alice Johnson', 'Engineering', 95000, tstzrange('2024-06-01', '2025-06-01', '[)')); +``` + +> [!IMPORTANT] +> The range column with `WITHOUT OVERLAPS` must be the last column in the primary key definition. + +## PERIOD for temporal foreign keys + +PostgreSQL 18 also introduces temporal foreign keys using the `PERIOD` clause. These constraints ensure that foreign key relationships are maintained across time periods, checking for range containment rather than simple equality. + +A temporal foreign key ensures that the referenced row exists during the entire time period of the referencing row. This is particularly useful when you need to enforce that related temporal data is valid for the same time periods. + +```csharp +public class Employee +{ + public int EmployeeId { get; set; } + public string Name { get; set; } + public NpgsqlRange ValidPeriod { get; set; } +} + +public class ProjectAssignment +{ + public int AssignmentId { get; set; } + public int EmployeeId { get; set; } + public string ProjectName { get; set; } + public NpgsqlRange AssignmentPeriod { get; set; } +} + +protected override void OnModelCreating(ModelBuilder modelBuilder) +{ + modelBuilder.Entity(b => + { + b.Property(e => e.ValidPeriod) + .HasDefaultValueSql("tstzrange(now(), 'infinity', '[)')"); + + b.HasKey(e => new { e.EmployeeId, e.ValidPeriod }) + .HasWithoutOverlaps(); + }); + + modelBuilder.Entity(b => + { + b.HasOne() + .WithMany() + .HasForeignKey(e => new { e.EmployeeId, e.AssignmentPeriod }) + .HasPrincipalKey(e => new { e.EmployeeId, e.ValidPeriod }) + .HasPeriod(); + }); +} +``` + +This generates a foreign key constraint like: + +```sql +ALTER TABLE project_assignments +ADD CONSTRAINT fk_emp_temporal +FOREIGN KEY (employee_id, PERIOD assignment_period) +REFERENCES employees (employee_id, PERIOD valid_period); +``` + +With this constraint: + +```sql +-- Valid: Assignment period falls within the employee's validity period +INSERT INTO project_assignments (employee_id, project_name, assignment_period) +VALUES (1, 'Website Redesign', tstzrange('2024-03-01', '2024-06-01', '[)')); + +-- Invalid: Assignment period extends beyond the employee's validity period +INSERT INTO project_assignments (employee_id, project_name, assignment_period) +VALUES (1, 'Legacy Project', tstzrange('2022-01-01', '2022-06-01', '[)')); +``` + +## Querying temporal data + +When querying temporal data, PostgreSQL's range operators are particularly useful. The containment operator (`@>`) checks if a range contains a specific point in time: + +```csharp +// Find employees who were active on a specific date +var activeEmployees = context.Employees + .Where(e => e.ValidPeriod.Contains(new DateTime(2024, 6, 15))) + .ToList(); + +// Find all historical records for a specific employee +var employeeHistory = context.Employees + .Where(e => e.EmployeeId == 1) + .OrderBy(e => e.ValidPeriod) + .ToList(); +``` + +These queries translate to efficient SQL that can leverage GiST indexes: + +```sql +-- Active employees on a specific date +SELECT * FROM employees +WHERE valid_period @> '2024-06-15'::timestamptz; + +-- Employee history +SELECT * FROM employees +WHERE employee_id = 1 +ORDER BY valid_period; +``` + +> [!NOTE] +> Temporal constraints require the `btree_gist` extension to be installed in your database. The EF provider automatically installs `btree_gist` when it detects a key with `WITHOUT OVERLAPS`. diff --git a/docs/release-notes/11.0.md b/docs/release-notes/11.0.md new file mode 100644 index 0000000000..2dded579d5 --- /dev/null +++ b/docs/release-notes/11.0.md @@ -0,0 +1,88 @@ +# 11.0 Release Notes + +Npgsql.EntityFrameworkCore.PostgreSQL version 11.0 is currently in development. Previews are available on [nuget.org](https://www.nuget.org/packages/Npgsql.EntityFrameworkCore.PostgreSQL). + +## Support for PostgreSQL 18 temporal constraints + +PostgreSQL 18 introduced powerful temporal constraints that allow enforcing data integrity over time periods directly at the database level. The EF Core provider now supports these features, allowing you to define temporal primary keys, unique constraints, and foreign keys. + +### WITHOUT OVERLAPS for keys + +Temporal primary and alternate keys use the `WITHOUT OVERLAPS` clause to ensure that for any given set of scalar column values, the associated time ranges do not overlap. This is useful for scenarios where you need to track historical data (e.g. employee records, pricing information, equipment assignments) while ensuring data integrity. + +For example, an employee can have multiple records in the database (reflecting changes over time), but their validity periods must never overlap: + +```csharp +public class Employee +{ + public int EmployeeId { get; set; } + public string Name { get; set; } + public string Department { get; set; } + public decimal Salary { get; set; } + public NpgsqlRange ValidPeriod { get; set; } +} + +protected override void OnModelCreating(ModelBuilder modelBuilder) +{ + modelBuilder.Entity(b => + { + b.Property(e => e.ValidPeriod) + .HasDefaultValueSql("tstzrange(now(), 'infinity', '[)')"); + + b.HasKey(e => new { e.EmployeeId, e.ValidPeriod }) + .HasWithoutOverlaps(); + }); +} +``` + +This generates the following SQL: + +```sql +CREATE TABLE employees ( + employee_id INTEGER, + name VARCHAR(100) NOT NULL, + department VARCHAR(50) NOT NULL, + salary DECIMAL(10,2) NOT NULL, + valid_period tstzrange NOT NULL DEFAULT tstzrange(now(), 'infinity', '[)'), + PRIMARY KEY (employee_id, valid_period WITHOUT OVERLAPS) +); +``` + +### PERIOD for temporal foreign keys + +Temporal foreign keys use the `PERIOD` clause to ensure that the referenced row exists during the entire time period of the referencing row. This maintains referential integrity across temporal relationships. + +For example, when assigning employees to projects, the assignment period must fall within the employee's validity period: + +```csharp +public class ProjectAssignment +{ + public int AssignmentId { get; set; } + public int EmployeeId { get; set; } + public string ProjectName { get; set; } + public NpgsqlRange AssignmentPeriod { get; set; } +} + +protected override void OnModelCreating(ModelBuilder modelBuilder) +{ + modelBuilder.Entity(b => + { + b.HasOne() + .WithMany() + .HasForeignKey(e => new { e.EmployeeId, e.AssignmentPeriod }) + .HasPrincipalKey(e => new { e.EmployeeId, e.ValidPeriod }) + .HasPeriod(); + }); +} +``` + +This generates the following SQL: + +```sql +ALTER TABLE project_assignments +ADD CONSTRAINT fk_emp_temporal +FOREIGN KEY (employee_id, PERIOD assignment_period) +REFERENCES employees (employee_id, PERIOD valid_period); +``` + +For more details, see the [temporal constraints documentation](../misc/temporal-constraints.md). diff --git a/docs/toc.yml b/docs/toc.yml index 0e71fa8271..1c4988380e 100644 --- a/docs/toc.yml +++ b/docs/toc.yml @@ -2,6 +2,8 @@ href: index.md - name: Release notes items: + - name: "11.0 (preview)" + href: release-notes/11.0.md - name: "10.0" href: release-notes/10.0.md - name: "9.0" @@ -62,6 +64,8 @@ href: misc/collations-and-case-sensitivity.md - name: Database creation href: misc/database-creation.md + - name: Temporal constraints + href: misc/temporal-constraints.md - name: Other href: misc/other.md - name: API reference From 60de374549c5f95dd052ae10873858eabd4e5a31 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Mon, 2 Feb 2026 11:51:46 +0100 Subject: [PATCH 192/207] Document IntersectsBbox (#447) See https://github.com/npgsql/efcore.pg/issues/3485 --- docs/mapping/nts.md | 17 +++++++++-------- docs/release-notes/11.0.md | 4 ++++ 2 files changed, 13 insertions(+), 8 deletions(-) diff --git a/docs/mapping/nts.md b/docs/mapping/nts.md index 893592eb2d..3ae651f52c 100644 --- a/docs/mapping/nts.md +++ b/docs/mapping/nts.md @@ -137,8 +137,8 @@ geom1.Difference(geom2) | [ST_Differenc geom1.Dimension | [ST_Dimension(geom1)](https://postgis.net/docs/ST_Dimension.html) geom1.Disjoint(geom2) | [ST_Disjoint(geom1, geom2)](https://postgis.net/docs/ST_Disjoint.html) geom1.Distance(geom2) | [ST_Distance(geom1, geom2)](https://postgis.net/docs/ST_Distance.html) -EF.Functions.DistanceKnn(geom1, geom2) | [geom1 <-> geom2](https://postgis.net/docs/geometry_distance_knn.html) | Added in 6.0 -EF.Functions.Distance(geom1, geom2, useSpheriod) | [ST_Distance(geom1, geom2, useSpheriod)](https://postgis.net/docs/ST_Distance.html) | Added in 6.0 +EF.Functions.DistanceKnn(geom1, geom2) | [geom1 <-> geom2](https://postgis.net/docs/geometry_distance_knn.html) +EF.Functions.Distance(geom1, geom2, useSpheriod) | [ST_Distance(geom1, geom2, useSpheriod)](https://postgis.net/docs/ST_Distance.html) geom1.Envelope | [ST_Envelope(geom1)](https://postgis.net/docs/ST_Envelope.html) geom1.ExactEquals(geom2) | [ST_OrderingEquals(geom1, geom2)](https://postgis.net/docs/ST_OrderingEquals.html) lineString.EndPoint | [ST_EndPoint(lineString)](https://postgis.net/docs/ST_EndPoint.html) @@ -146,18 +146,19 @@ polygon.ExteriorRing | [ST_ExteriorR geom1.Equals(geom2) | [geom1 = geom2](https://postgis.net/docs/ST_Geometry_EQ.html) geom1.Polygon.EqualsExact(geom2) | [geom1 = geom2](https://postgis.net/docs/ST_Geometry_EQ.html) geom1.EqualsTopologically(geom2) | [ST_Equals(geom1, geom2)](https://postgis.net/docs/ST_Equals.html) -EF.Functions.Force2D | [ST_Force2D(geom)](https://postgis.net/docs/ST_Force2D.html) | Added in 6.0 +EF.Functions.Force2D | [ST_Force2D(geom)](https://postgis.net/docs/ST_Force2D.html) geom.GeometryType | [GeometryType(geom)](https://postgis.net/docs/GeometryType.html) geomCollection.GetGeometryN(i) | [ST_GeometryN(geomCollection, i)](https://postgis.net/docs/ST_GeometryN.html) linestring.GetPointN(i) | [ST_PointN(linestring, i)](https://postgis.net/docs/ST_PointN.html) geom1.Intersection(geom2) | [ST_Intersection(geom1, geom2)](https://postgis.net/docs/ST_Intersection.html) geom1.Intersects(geom2) | [ST_Intersects(geom1, geom2)](https://postgis.net/docs/ST_Intersects.html) +EF.Functions.IntersectsBbox(geom1, geom2) | [geom1 && geom2](https://postgis.net/docs/geometry_overlaps.html) | Added in 11.0 geom.InteriorPoint | [ST_PointOnSurface(geom)](https://postgis.net/docs/ST_PointOnSurface.html) lineString.IsClosed() | [ST_IsClosed(lineString)](https://postgis.net/docs/ST_IsClosed.html) geomCollection.IsEmpty() | [ST_IsEmpty(geomCollection)](https://postgis.net/docs/ST_IsEmpty.html) linestring.IsRing | [ST_IsRing(linestring)](https://postgis.net/docs/ST_IsRing.html) geom.IsWithinDistance(geom2,d) | [ST_DWithin(geom1, geom2, d)](https://postgis.net/docs/ST_DWithin.html) -EF.Functions.IsWithinDistance(geom1, geom2, d, useSpheriod) | [ST_DWithin(geom1, geom2, d, useSpheriod)](https://postgis.net/docs/ST_DWithin.html) | Added in 6.0 +EF.Functions.IsWithinDistance(geom1, geom2, d, useSpheriod) | [ST_DWithin(geom1, geom2, d, useSpheriod)](https://postgis.net/docs/ST_DWithin.html) geom.IsSimple() | [ST_IsSimple(geom)](https://postgis.net/docs/ST_IsSimple.html) geom.IsValid() | [ST_IsValid(geom)](https://postgis.net/docs/ST_IsValid.html) lineString.Length | [ST_Length(lineString)](https://postgis.net/docs/ST_Length.html) @@ -182,7 +183,7 @@ point.M | [ST_M(point)] point.X | [ST_X(point)](https://postgis.net/docs/ST_X.html) point.Y | [ST_Y(point)](https://postgis.net/docs/ST_Y.html) point.Z | [ST_Z(point)](https://postgis.net/docs/ST_Z.html) -UnaryUnionOp.Union(geometries) | [ST_Union(geometries)](https://postgis.net/docs/ST_Union.html) | Added in 7.0, see [Aggregate functions](translations.md#aggregate-functions). -GeometryCombiner.Combine(geometries) | [ST_Collect(geometries)](https://postgis.net/docs/ST_Collect.html) | Added in 7.0, see [Aggregate functions](translations.md#aggregate-functions). -EnvelopeCombiner.CombineAsGeometry(geometries) | [ST_Extent(geometries)::geometry](https://postgis.net/docs/ST_Extent.html) | Added in 7.0, see [Aggregate functions](translations.md#aggregate-functions). -ConvexHull.Create(geometries) | [ST_ConvexHull(geometries)](https://postgis.net/docs/ST_ConvexHull.html) | Added in 7.0, see [Aggregate functions](translations.md#aggregate-functions). +UnaryUnionOp.Union(geometries) | [ST_Union(geometries)](https://postgis.net/docs/ST_Union.html) | See [Aggregate functions](translations.md#aggregate-functions). +GeometryCombiner.Combine(geometries) | [ST_Collect(geometries)](https://postgis.net/docs/ST_Collect.html) | See [Aggregate functions](translations.md#aggregate-functions). +EnvelopeCombiner.CombineAsGeometry(geometries) | [ST_Extent(geometries)::geometry](https://postgis.net/docs/ST_Extent.html) | See [Aggregate functions](translations.md#aggregate-functions). +ConvexHull.Create(geometries) | [ST_ConvexHull(geometries)](https://postgis.net/docs/ST_ConvexHull.html) | See [Aggregate functions](translations.md#aggregate-functions). diff --git a/docs/release-notes/11.0.md b/docs/release-notes/11.0.md index 2dded579d5..53166ad316 100644 --- a/docs/release-notes/11.0.md +++ b/docs/release-notes/11.0.md @@ -86,3 +86,7 @@ REFERENCES employees (employee_id, PERIOD valid_period); ``` For more details, see the [temporal constraints documentation](../misc/temporal-constraints.md). + +## Other new features + +* Added `EF.Functions.IntersectsBbox(geom1, geom2)` for expressing [the PostGIS `&&` operator](https://postgis.net/docs/geometry_overlaps.html). Thanks to [@bjornharrtell](https://github.com/bjornharrtell) for this contribution! From 31f95720fc4f531cba00de8f1e2a3800473bf747 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Tue, 31 Mar 2026 10:00:29 +0300 Subject: [PATCH 193/207] Document EFCore.PG targeting PostgreSQL version 16 by default (#454) See https://github.com/npgsql/efcore.pg/issues/3798 --- docs/release-notes/11.0.md | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/docs/release-notes/11.0.md b/docs/release-notes/11.0.md index 53166ad316..fdac2d3083 100644 --- a/docs/release-notes/11.0.md +++ b/docs/release-notes/11.0.md @@ -90,3 +90,12 @@ For more details, see the [temporal constraints documentation](../misc/temporal- ## Other new features * Added `EF.Functions.IntersectsBbox(geom1, geom2)` for expressing [the PostGIS `&&` operator](https://postgis.net/docs/geometry_overlaps.html). Thanks to [@bjornharrtell](https://github.com/bjornharrtell) for this contribution! + +## Breaking changes + +* The provider now assumes at least PostgreSQL 16 by default, taking advantage of newer features (previously, PostgreSQL 14 was targeted). You can configure the targeted PostgreSQL version when configuring your context: + +```c# +protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) + => optionsBuilder.UseNpgsql("", o => o.SetPostgresVersion(14, 0)); +``` From d5308b2811af6f5f64686830cf9be148ccdc5a1d Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Thu, 2 Jul 2026 12:51:43 +0200 Subject: [PATCH 194/207] Document 10.0 array Contains breaking SQL translation change (#464) --- docs/release-notes/10.0.md | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/docs/release-notes/10.0.md b/docs/release-notes/10.0.md index b57db74bc4..993247030c 100644 --- a/docs/release-notes/10.0.md +++ b/docs/release-notes/10.0.md @@ -159,5 +159,31 @@ See the [10.0.0 milestone](https://github.com/npgsql/efcore.pg/milestone/68?clos ## Breaking changes +### Array `Contains` translation now defaults to `ANY` + +Translation for array `Contains` was changed in 10.0: `arrayColumn.Contains(element)` now defaults to `element = ANY(arrayColumn)` (instead of `arrayColumn @> ARRAY[element]`). This can impact performance depending on your indexes: `@>` can be much faster with a GIN index over the array column, while `ANY` can be better when that GIN index is missing. + +Previous SQL: + +```sql +WHERE array_column @> ARRAY[@__element_0]::text[] +``` + +New default SQL: + +```sql +WHERE @__element_0 = ANY (array_column) +``` + +To tell EF that a GIN index exists and revert to the previous `@>` translation, model that index: + +```csharp +modelBuilder.Entity() + .HasIndex(i => i.ArrayColumn) + .HasMethod("gin"); +``` + +### Other breaking changes + * `EF.Functions.Network()` and `EF.Functions.Merge()` have been changed to return the new .NET [`IPNetwork`](https://learn.microsoft.com/dotnet/api/system.net.ipnetwork) instead of the obsolete `NpgsqlCidr`. The new `IPNetwork` type works with all other functions as well (but no breaking changes were necessary). * The PostgreSQL network type `cidr` is now scaffolded to the new .NET [`IPNetwork`](https://learn.microsoft.com/dotnet/api/system.net.ipnetwork) type. The older Npgsql representation for `cidr` - the `NpgsqlCidr` type - has been obsoleted and will be removed in a future release. From dbd8e9e2a0f9802c37691180ef4b85eb79311c0f Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Mon, 12 Oct 2026 13:31:04 +0200 Subject: [PATCH 195/207] Document explicit-source timezone conversion translation (#471) Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: dab05258-0495-467d-920c-8b811a77bdf8 --- docs/mapping/translations.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/mapping/translations.md b/docs/mapping/translations.md index d9433e5b68..01cf54ff81 100644 --- a/docs/mapping/translations.md +++ b/docs/mapping/translations.md @@ -101,6 +101,7 @@ timeSpan.TotalDays | [date_part(' timeSpan.TotalHours | [date_part('epoch', interval) / 3600.0](https://www.postgresql.org/docs/current/functions-datetime.html) | dateTime1 - dateTime2 | [dateTime1 - dateTime2](https://www.postgresql.org/docs/current/functions-datetime.html#OPERATORS-DATETIME-TABLE) | TimeZoneInfo.ConvertTimeBySystemTimeZoneId(utcDateTime, timezone) | [utcDateTime AT TIME ZONE timezone](https://www.postgresql.org/docs/current/functions-datetime.html#FUNCTIONS-DATETIME-ZONECONVERT) | Only for timestamptz columns +TimeZoneInfo.ConvertTimeBySystemTimeZoneId(dateTime, sourceTimeZoneId, destinationTimeZoneId) | [(dateTime AT TIME ZONE sourceTimeZoneId) AT TIME ZONE destinationTimeZoneId](https://www.postgresql.org/docs/current/functions-datetime.html#FUNCTIONS-DATETIME-ZONECONVERT) | Added in 11.0. Requires timestamp without time zone input; returns timestamp without time zone (`DateTimeKind.Unspecified`), even for UTC destinations. Not supported for `DateTimeOffset`. TimeZoneInfo.ConvertTimeToUtc(nonUtcDateTime) | [nonUtcDateTime::timestamptz](https://www.postgresql.org/docs/current/functions-datetime.html) | Only for timestamp columns DateTime.SpecifyKind(utcDateTime, DateTimeKind.Unspecified) | [utcDateTime AT TIME ZONE 'UTC'](https://www.postgresql.org/docs/current/functions-datetime.html#FUNCTIONS-DATETIME-ZONECONVERT) | Only for timestamptz columns DateTime.SpecifyKind(nonUtcDateTime, DateTimeKind.Utc) | [nonUtcDateTime AT TIME ZONE 'UTC'](https://www.postgresql.org/docs/current/functions-datetime.html#FUNCTIONS-DATETIME-ZONECONVERT) | Only for timestamp columns From 90ba6482cb12ab20a817255444b0ec52b4516fd0 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Thu, 15 Oct 2026 15:28:40 +0200 Subject: [PATCH 196/207] Document Daitch-Mokotoff translation (#472) Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: bef3c291-4d50-4144-83a8-609d01f54c7a --- docs/mapping/translations.md | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/docs/mapping/translations.md b/docs/mapping/translations.md index 01cf54ff81..4eb9dabbd2 100644 --- a/docs/mapping/translations.md +++ b/docs/mapping/translations.md @@ -234,12 +234,13 @@ EF.Functions.TrigramsStrictWordSimilarityDistanceInverted(s1, s2) | s1 <-> ## Fuzzy string match functions -The below translations provide functionality for determining similarities and distance between strings, using the [`pg_trgm`](https://www.postgresql.org/docs/current/pgtrgm.html) extension which is bundled with standard PostgreSQL distributions. +The below translations provide functionality for determining similarities and distance between strings, using the [`fuzzystrmatch`](https://www.postgresql.org/docs/current/fuzzystrmatch.html) extension which is bundled with standard PostgreSQL distributions. -.NET | SQL ------------------------------------------------------------------------------------------------------- | -------------------- +.NET | SQL | Notes +------------------------------------------------------------------------------------------------------ | -------------------- | ----- EF.Functions.FuzzyStringMatchSoundex(text) | [soundex(text)](https://www.postgresql.org/docs/current/fuzzystrmatch.html#FUZZYSTRMATCH-SOUNDEX) EF.Functions.FuzzyStringMatchDifference(source, target) | [difference(source, target)](https://www.postgresql.org/docs/current/fuzzystrmatch.html#FUZZYSTRMATCH-SOUNDEX) +EF.Functions.FuzzyStringMatchDaitchMokotoff(text) | [daitch_mokotoff(text)](https://www.postgresql.org/docs/current/fuzzystrmatch.html#FUZZYSTRMATCH-DAITCH-MOKOTOFF) | Added in 11.0. Requires PostgreSQL 16+ EF.Functions.FuzzyStringMatchLevenshtein(source, target) | [levenshtein(source, target)](https://www.postgresql.org/docs/current/fuzzystrmatch.html#FUZZYSTRMATCH-LEVENSHTEIN) EF.Functions.FuzzyStringMatchLevenshtein(source, target, ins_cost, del_cost, sub_cost) | [levenshtein(source, target, ins_cost, del_cost, sub_cost)](https://www.postgresql.org/docs/current/fuzzystrmatch.html#FUZZYSTRMATCH-LEVENSHTEIN) EF.Functions.FuzzyStringMatchLevenshteinLessEqual(source, target, max_d) | [levenshtein(source, target, max_d)](https://www.postgresql.org/docs/current/fuzzystrmatch.html#FUZZYSTRMATCH-LEVENSHTEIN) @@ -248,6 +249,8 @@ EF.Functions.FuzzyStringMatchMetaphone(text, max_output_length) EF.Functions.FuzzyStringMatchDoubleMetaphone(text) | [dmetaphone(text)](https://www.postgresql.org/docs/current/fuzzystrmatch.html#FUZZYSTRMATCH-METAPHONE) EF.Functions.FuzzyStringMatchDoubleMetaphoneAlt(text) | [dmetaphone_alt(text)](https://www.postgresql.org/docs/current/fuzzystrmatch.html#FUZZYSTRMATCH-METAPHONE) +`FuzzyStringMatchDaitchMokotoff` returns `string[]?`, with `null` possible for inputs without encodable characters, including empty strings. Projection and array indexing are supported, but composing `Contains`, `Any`, `Intersect(...).Any()`, or `.Length` on the result is not currently translated ([dotnet/efcore#35980](https://github.com/dotnet/efcore/issues/35980)). + ## LTree functions The below translations are for working with label trees from the PostgreSQL [`ltree`](https://www.postgresql.org/docs/current/ltree.html) extension. Use the type to represent ltree and invoke methods on it in EF Core LINQ queries. From b0583efc1c788178d0a72e78d32f5928846caec4 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Fri, 16 Oct 2026 12:06:49 +0200 Subject: [PATCH 197/207] Document EF 11 JSON member indexes (#474) Add JSON mapping examples and index selection guidance, with an EF 11 release-note entry and temporary RC2 limitations. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 8e44980c-ccf7-431f-bc01-da8135db9db0 --- docs/mapping/json.md | 54 +++++++++++++++++++++++++++++++++++++- docs/release-notes/11.0.md | 7 +++++ 2 files changed, 60 insertions(+), 1 deletion(-) diff --git a/docs/mapping/json.md b/docs/mapping/json.md index 462e70714a..f4ce0edb31 100644 --- a/docs/mapping/json.md +++ b/docs/mapping/json.md @@ -284,5 +284,57 @@ EF.Functions.JsonTypeof(e.Customer.Age) ## Indexing JSON columns +Choose an index based on the operators used by your queries: targeted B-tree expression indexes support comparisons on extracted scalar values, while GIN indexes support matching containment, key-existence and JSON-path predicates over `jsonb` values. + +### Indexing members with ToJson + > [!NOTE] -> A section on indices will be added. In the meantime consult the PostgreSQL documentation and other guides on the Internet. +> Indexing JSON members was introduced in EF 11. + +You can use the existing `HasIndex` APIs to index members of complex types mapped with `ToJson()`. Using the Customer model above: + +```csharp +protected override void OnModelCreating(ModelBuilder modelBuilder) +{ + modelBuilder.Entity(b => + { + b.ComplexProperty(c => c.Details, d => d.ToJson()); + + b.HasIndex(c => c.Details.Name).IsUnique(); + b.HasIndex(c => new { c.Details.Name, c.Details.Age }); + b.HasIndex(c => c.Details.Orders[0].Price); + }); +} +``` + +By default, these produce B-tree expression indexes over the selected members, not indexes over the entire JSON document. The expressions extract values with the same conversions as LINQ queries; for example, `Name` is extracted as text, while `Age` is cast to an integer. These indexes can support equality and range comparisons, ordering, and uniqueness where applicable. + +Nested paths, configured JSON property names, fixed collection positions (such as `Orders[0].Price`) and array values themselves are supported. Composite member indexes must refer to the same JSON column. Existing index options, such as sort order and the [PostgreSQL-specific index configuration](../modeling/indexes.md), also apply. + +The following limitations apply: + +* Wildcard traversal to descendants of all collection elements is not supported; selecting a fixed position does not index that member in every element. +* EF does not allow combining JSON member keys with regular column keys or members from multiple JSON columns, or creating unique indexes over entire JSON complex objects. +* Nested JSON member indexes cannot be combined with `IsTsVectorExpressionIndex`. +* PostgreSQL requires index expressions to be `IMMUTABLE`. Some native date/time and enum casts are not immutable, so PostgreSQL rejects indexes whose expressions require those casts. + +### GIN indexes + +Whole-document GIN indexes remain supported as before. You can also explicitly select GIN for an array or subdocument within a `jsonb` column: + +```csharp +modelBuilder.Entity() + .HasIndex(c => c.Details) + .HasMethod("gin"); + +modelBuilder.Entity() + .HasIndex(c => c.Details.Orders) + .HasMethod("gin") + .HasOperators("jsonb_path_ops"); +``` + +A whole-document GIN index can cover predicates on many properties, while a targeted index covers a selected expression. Queries must use matching expressions and operators: a GIN index on the document does not accelerate ordinary comparisons on extracted scalars, such as `c.Details.Age > 18`. Similarly, an index on `Details.Orders` serves supported predicates on that array, not arbitrary comparisons on each order's `Price`. + +The default `jsonb_ops` GIN operator class supports containment, key-existence and JSON-path operators. The alternative `jsonb_path_ops` supports containment and JSON-path operators, but not key-existence operators (`?`, `?|`, `?&`). A document-wide GIN index is not necessarily smaller or cheaper to maintain than targeted B-tree indexes; choose based on your queries and workload. + +See [PostgreSQL's JSON indexing documentation](https://www.postgresql.org/docs/current/datatype-json.html#JSON-INDEXING) for details on supported operators and index tradeoffs. diff --git a/docs/release-notes/11.0.md b/docs/release-notes/11.0.md index fdac2d3083..e8321e2e61 100644 --- a/docs/release-notes/11.0.md +++ b/docs/release-notes/11.0.md @@ -2,6 +2,13 @@ Npgsql.EntityFrameworkCore.PostgreSQL version 11.0 is currently in development. Previews are available on [nuget.org](https://www.nuget.org/packages/Npgsql.EntityFrameworkCore.PostgreSQL). +## Indexes over JSON members + +EF 11 complex types mapped with `ToJson()` now support indexing JSON members through the existing `HasIndex` APIs, including unique and composite indexes. By default, these create B-tree expression indexes over the selected values; explicit GIN indexes can target `jsonb` arrays and subdocuments. See [Indexing JSON columns](../mapping/json.md#indexing-json-columns) for examples and limitations. + +> [!NOTE] +> The provider currently references EF `11.0.0-rc.2.26504.105`, which has two temporary limitations: C# migration scaffolding for JSON member indexes fails because it cannot scaffold a `RelationalJsonIndex` literal, and composite member indexes with mixed ascending/descending directions fail before SQL generation. Uniform ascending or descending composites can generate SQL, but remain affected by the scaffolding limitation. Both issues are fixed in [dotnet/efcore#39089](https://github.com/dotnet/efcore/pull/39089); the provider has not yet consumed those fixes. + ## Support for PostgreSQL 18 temporal constraints PostgreSQL 18 introduced powerful temporal constraints that allow enforcing data integrity over time periods directly at the database level. The EF Core provider now supports these features, allowing you to define temporal primary keys, unique constraints, and foreign keys. From ab85e5eb13c5628a39233fb3d0bad86a522bea67 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Mon, 19 Oct 2026 11:53:35 +0200 Subject: [PATCH 198/207] Document EFCore.PG 11 features and breaking changes (#475) Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 635ffab7-59a4-4bc8-bf5a-73e707d381cf --- docs/mapping/array.md | 1 + docs/mapping/json.md | 8 ++--- docs/mapping/nodatime.md | 4 +++ docs/mapping/translations.md | 50 +++++++++++++++++++++------ docs/misc/temporal-constraints.md | 16 +++++++-- docs/modeling/concurrency.md | 6 ++++ docs/modeling/generated-properties.md | 9 +++++ docs/release-notes/11.0.md | 47 ++++++++++++++++++++++--- 8 files changed, 119 insertions(+), 22 deletions(-) diff --git a/docs/mapping/array.md b/docs/mapping/array.md index 47b1126301..15b72215f0 100644 --- a/docs/mapping/array.md +++ b/docs/mapping/array.md @@ -34,6 +34,7 @@ array.Take(2) | [array\[,2\]](https://www.postgr array.Skip(1).Take(2) | [array\[2,3\]](https://www.postgresql.org/docs/current/arrays.html#ARRAYS-ACCESSING) | Added in 8.0 array1 == array2 | [array1 = array2](https://www.postgresql.org/docs/current/static/arrays.html) | array1.SequenceEqual(array2) | [array1 = array2](https://www.postgresql.org/docs/current/static/arrays.html) | +array1.Take(2).SequenceEqual(array2) | [array1\[:2\] = array2](https://www.postgresql.org/docs/current/arrays.html#ARRAYS-ACCESSING) | Added in 11.0; also supports Skip() and Skip().Take() arrayNonColumn.Contains(element) | [element = ANY(arrayNonColumn)](https://www.postgresql.org/docs/current/static/functions-comparisons.html#AEN21104) | Can use regular index arrayColumn.Contains(element) | [arrayColumn @> ARRAY\[element\]](https://www.postgresql.org/docs/current/functions-array.html#ARRAY-OPERATORS-TABLE) | Can use GIN index array.Append(element) | [array_append(array, element)](https://www.postgresql.org/docs/current/functions-array.html#ARRAY-FUNCTIONS-TABLE) | Added in 6.0 diff --git a/docs/mapping/json.md b/docs/mapping/json.md index f4ce0edb31..09df8eef5c 100644 --- a/docs/mapping/json.md +++ b/docs/mapping/json.md @@ -260,8 +260,8 @@ customer.RootElement.GetProperty("Orders").GetArrayLength() EF.Functions.JsonContains(customer, @"{""Name"": ""Joe"", ""Age"": 25}")1 | [customer @> '{"Name": "Joe", "Age": 25}'](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) EF.Functions.JsonContained(@"{""Name"": ""Joe"", ""Age"": 25}", customer)1 | ['{"Name": "Joe", "Age": 25}' <@ customer](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) EF.Functions.JsonExists(customer, "Age") | [customer ? 'Age'](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) -EF.Functions.JsonExistsAny(customer, "Age", "Address") | [customer ?\| ARRAY\['Age','Address'\]](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) -EF.Functions.JsonExistsAll(customer, "Age", "Address") | [customer ?& ARRAY\['Age','Address'\]](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) +EF.Functions.JsonExistAny(customer, "Age", "Address") | [customer ?\| ARRAY\['Age','Address'\]](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) +EF.Functions.JsonExistAll(customer, "Age", "Address") | [customer ?& ARRAY\['Age','Address'\]](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) EF.Functions.JsonTypeof(customer.GetProperty("Age")) == "number" | [jsonb_typeof(customer->'Age') = 'number'](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-PROCESSING-TABLE) ### [Legacy POCO Mapping](#tab/poco) @@ -274,8 +274,8 @@ customer.Orders.Length (or Count) EF.Functions.JsonContains(customer, @"{""Name"": ""Joe"", ""Age"": 25}")1 | [customer @> '{"Name": "Joe", "Age": 25}'](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) EF.Functions.JsonContained(@"{""Name"": ""Joe"", ""Age"": 25}", e.Customer)1 | ['{"Name": "Joe", "Age": 25}' <@ customer](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) EF.Functions.JsonExists(e.Customer, "Age") | [customer ? 'Age'](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) -EF.Functions.JsonExistsAny(e.Customer, "Age", "Address") | [customer ?\| ARRAY\['Age','Address'\]](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) -EF.Functions.JsonExistsAll(e.Customer, "Age", "Address") | [customer ?& ARRAY\['Age','Address'\]](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) +EF.Functions.JsonExistAny(e.Customer, "Age", "Address") | [customer ?\| ARRAY\['Age','Address'\]](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) +EF.Functions.JsonExistAll(e.Customer, "Age", "Address") | [customer ?& ARRAY\['Age','Address'\]](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) EF.Functions.JsonTypeof(e.Customer.Age) | [jsonb_typeof(customer->'Age')](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-PROCESSING-TABLE) *** diff --git a/docs/mapping/nodatime.md b/docs/mapping/nodatime.md index ff31884dd9..a24c1542c4 100644 --- a/docs/mapping/nodatime.md +++ b/docs/mapping/nodatime.md @@ -82,9 +82,13 @@ var oldEvents = context.Events.Where(p => p.SomeDate.Year < 2000); Following is the list of supported NodaTime translations; If an operation you need is missing, please open an issue to request for it. +Starting with version 11.0, `EF.Functions.DateTrunc()` supports `LocalDateTime`, `Instant`, `ZonedDateTime`, `Period` and `Duration`. Its optional time zone argument is only supported for `Instant` and `ZonedDateTime` mapped to `timestamp with time zone`; without that argument, PostgreSQL uses the session time zone for these values. + .NET | SQL | Notes -------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ | ----------- SystemClock.Instance.GetCurrentInstant() | [now()](https://www.postgresql.org/docs/current/functions-datetime.html) | +EF.Functions.DateTrunc("month", value) | [date_trunc('month', value)](https://www.postgresql.org/docs/current/functions-datetime.html) | Added in 11.0 +EF.Functions.DateTrunc("month", instant, "Europe/Berlin") | [date_trunc('month', instant, 'Europe/Berlin')](https://www.postgresql.org/docs/current/functions-datetime.html) | Added in 11.0 LocalDateTime.Date | [date_trunc('day', timestamp)](https://www.postgresql.org/docs/current/functions-datetime.html) | LocalDateTime.Second (also LocalTime, ZonedDateTime) | [date_part('second', timestamp)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | LocalDateTime.Minute (also LocalTime, ZonedDateTime) | [date_part('minute', timestamp)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | diff --git a/docs/mapping/translations.md b/docs/mapping/translations.md index 4eb9dabbd2..2d0151be9b 100644 --- a/docs/mapping/translations.md +++ b/docs/mapping/translations.md @@ -18,18 +18,18 @@ string.Concat(str0, str1) | str0 \|\| str1 string.IsNullOrEmpty(value) | value IS NULL OR value = '' string.IsNullOrWhiteSpace(value) | value IS NULL OR btrim(value, E' \t\n\r') = '' stringValue.CompareTo(strB) | CASE WHEN stringValue = strB THEN 0 ... END -stringValue.Contains(value) | stringValue LIKE %value% -stringValue.EndsWith(value) | stringValue LIKE '%' \|\| value +stringValue.Contains(value) | stringValue LIKE %value% | char overload added in 11.0 +stringValue.EndsWith(value) | stringValue LIKE '%' \|\| value | char overload added in 11.0 stringValue.FirstOrDefault() | substr(stringValue, 1, 1) -stringValue.IndexOf(value) | strpos(stringValue, value) - 1 +stringValue.IndexOf(value) | strpos(stringValue, value) - 1 | char overload added in 11.0 stringValue.LastOrDefault() | substr(stringValue, length(stringValue), 1) stringValue.Length | length(stringValue) -stringValue.PadLeft(length) | lpad(stringValue, length) -stringValue.PadLeft(length, char) | lpad(stringValue, length, char) -stringValue.PadRight(length) | rpad(stringValue, length) -stringValue.PadRight(length, char) | rpad(stringValue, length, char) -stringValue.Replace(oldValue, newValue) | replace(stringValue, oldValue, newValue) -stringValue.StartsWith(value) | stringValue LIKE value \|\| '%' +stringValue.PadLeft(length) | CASE WHEN length(stringValue) >= length THEN stringValue ELSE lpad(stringValue, length) END +stringValue.PadLeft(length, char) | CASE WHEN length(stringValue) >= length THEN stringValue ELSE lpad(stringValue, length, char) END +stringValue.PadRight(length) | CASE WHEN length(stringValue) >= length THEN stringValue ELSE rpad(stringValue, length) END +stringValue.PadRight(length, char) | CASE WHEN length(stringValue) >= length THEN stringValue ELSE rpad(stringValue, length, char) END +stringValue.Replace(oldValue, newValue) | replace(stringValue, oldValue, newValue) | char overload added in 11.0 +stringValue.StartsWith(value) | stringValue LIKE value \|\| '%' | char overload added in 11.0 stringValue.Substring(startIndex, length) | substr(stringValue, startIndex + 1, @length) stringValue.ToLower() | lower(stringValue) stringValue.ToUpper() | upper(stringValue) @@ -57,6 +57,8 @@ EF.Functions.StringToArray(s, "\|", "FOO") | [string_agg(s, ' > > See also Npgsql's [NodaTime support](/efcore/mapping/nodatime.html), which is a better and safer way of interacting with date/time data. +Starting with version 11.0, `EF.Functions.DateTrunc()` supports `DateTime`, `DateTimeOffset` and `TimeSpan`. The optional time zone argument is only supported for values mapped to `timestamp with time zone`; when omitted for such values, PostgreSQL uses the session time zone. + .NET | SQL | Notes ----------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- | -------- DateTime.UtcNow (6.0+) | [now()](https://www.postgresql.org/docs/current/functions-datetime.html) | @@ -65,6 +67,8 @@ DateTime.Today (6.0+) | [date_trunc( DateTime.UtcNow (legacy) | [now() AT TIME ZONE 'UTC'](https://www.postgresql.org/docs/current/functions-datetime.html) | DateTime.Now (legacy) | [now()](https://www.postgresql.org/docs/current/functions-datetime.html) | DateTime.Today (legacy) | [date_trunc('day', now())](https://www.postgresql.org/docs/current/functions-datetime.html) | +EF.Functions.DateTrunc("month", value) | [date_trunc('month', value)](https://www.postgresql.org/docs/current/functions-datetime.html) | Added in 11.0 +EF.Functions.DateTrunc("month", utcDateTime, "Europe/Berlin") | [date_trunc('month', utcDateTime, 'Europe/Berlin')](https://www.postgresql.org/docs/current/functions-datetime.html) | Added in 11.0; timestamp with time zone only dateTime.AddDays(1) | [dateTime + INTERVAL '1 days'](https://www.postgresql.org/docs/current/functions-datetime.html#OPERATORS-DATETIME-TABLE) | dateTime.AddHours(value) | [dateTime + INTERVAL '1 hours'](https://www.postgresql.org/docs/current/functions-datetime.html#OPERATORS-DATETIME-TABLE) | dateTime.AddMinutes(1) | [dateTime + INTERVAL '1 minutes'](https://www.postgresql.org/docs/current/functions-datetime.html#OPERATORS-DATETIME-TABLE) | @@ -111,16 +115,38 @@ new DateTime(y, m, d, h, m, s, kind) | [make_timest EF.Functions.Sum(timespans) | [sum(timespans)](https://www.postgresql.org/docs/current/functions-aggregate.html#FUNCTIONS-AGGREGATE-TABLE) | See [Aggregate functions](#aggregate-functions). EF.Functions.Average(timespans) | [avg(timespans)](https://www.postgresql.org/docs/current/functions-aggregate.html#FUNCTIONS-AGGREGATE-TABLE) | See [Aggregate functions](#aggregate-functions). +## JSON functions + +See [JSON mapping](json.md) for mapping options and [PostgreSQL's JSON functions and operators](https://www.postgresql.org/docs/current/functions-json.html) for operator semantics. JSON aggregate functions are listed under [Aggregate functions](#aggregate-functions). + +.NET | SQL | Notes +----------------------------------------------- | ------------------------------------ | ----- +EF.Functions.JsonContains(json, contained) | json @> contained | jsonb only +EF.Functions.JsonContained(contained, json) | contained <@ json | jsonb only +EF.Functions.JsonExists(json, key) | json ? key | jsonb only +EF.Functions.JsonExistAny(json, key1, key2) | json ?\| ARRAY[key1, key2] | jsonb only +EF.Functions.JsonExistAll(json, key1, key2) | json ?& ARRAY[key1, key2] | jsonb only +EF.Functions.JsonTypeof(json) | jsonb_typeof(json) or json_typeof(json) | Selected according to the mapped column type +EF.Functions.JsonPathExists(json, "$.Age") | JSON_EXISTS(json, '$.Age') | Added in 11.0; requires PostgreSQL 17 or above + ## Miscellaneous functions -.NET | SQL ----------------------------------------- | -------------------- +.NET | SQL | Notes +---------------------------------------- | -------------------- | ----- collection.Contains(item) | item IN collection enumValue.HasFlag(flag) | enumValue & flag = flag Guid.CreateVersion7() | [uuidv7()](https://www.postgresql.org/docs/current/functions-uuid.html) (added in 10 when targeting PG18, client-evaluated otherwise) Guid.NewGuid() | [gen_random_uuid()](https://www.postgresql.org/docs/current/functions-uuid.html), or [uuid_generate_v4()](https://www.postgresql.org/docs/current/uuid-ossp.html) from [`uuid-ossp`](https://www.postgresql.org/docs/current/uuid-ossp.html) when targeting pre-PG13 nullable.GetValueOrDefault() | coalesce(nullable, 0) nullable.GetValueOrDefault(defaultValue) | coalesce(nullable, defaultValue) +bool.Parse(stringValue) | CAST(stringValue AS boolean) | Added in 11.0 +byte.Parse(stringValue) | CAST(stringValue AS smallint) | Added in 11.0 +short.Parse(stringValue) | CAST(stringValue AS smallint) | Added in 11.0 +int.Parse(stringValue) | CAST(stringValue AS integer) | Added in 11.0 +long.Parse(stringValue) | CAST(stringValue AS bigint) | Added in 11.0 +float.Parse(stringValue) | CAST(stringValue AS real) | Added in 11.0 +double.Parse(stringValue) | CAST(stringValue AS double precision) | Added in 11.0 +decimal.Parse(stringValue) | CAST(stringValue AS numeric) | Added in 11.0 ## Binary functions @@ -128,6 +154,7 @@ nullable.GetValueOrDefault(defaultValue) | coalesce(nullable, defaultValue) ---------------------------- | ------------------------------- | -------- bytes[i] | get_byte(bytes, i) | bytes.Contains(value) | position(value IN bytes) > 0 | +bytes.Any() | length(bytes) > 0 | Added in 11.0 bytes.Length | length(@bytes) | bytes1.SequenceEqual(bytes2) | @bytes = @second | @@ -315,6 +342,7 @@ The PostgreSQL aggregate functions are documented [here](https://www.postgresql. | EF.Functions.Sum(timespans) | sum(timespans) | EF.Functions.Average(timespans) | avg(timespans) | EF.Functions.JsonObjectAgg(tuple_of_2) | json_object_agg(tuple_of_2.first, tuple_of_2.second) +| EF.Functions.JsonbObjectAgg(tuple_of_2) | jsonb_object_agg(tuple_of_2.first, tuple_of_2.second) | ranges.RangeAgg() | range_agg(ranges) | ranges.RangeIntersectAgg() | range_intersect_agg(ranges) | multiranges.RangeIntersectAgg() | range_intersect_agg(multiranges) diff --git a/docs/misc/temporal-constraints.md b/docs/misc/temporal-constraints.md index c817296437..950961ebac 100644 --- a/docs/misc/temporal-constraints.md +++ b/docs/misc/temporal-constraints.md @@ -33,7 +33,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) // Configure the temporal primary key b.HasKey(e => new { e.EmployeeId, e.ValidPeriod }) - .HasWithoutOverlaps(); + .WithoutOverlaps(); }); } ``` @@ -98,7 +98,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) .HasDefaultValueSql("tstzrange(now(), 'infinity', '[)')"); b.HasKey(e => new { e.EmployeeId, e.ValidPeriod }) - .HasWithoutOverlaps(); + .WithoutOverlaps(); }); modelBuilder.Entity(b => @@ -107,7 +107,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) .WithMany() .HasForeignKey(e => new { e.EmployeeId, e.AssignmentPeriod }) .HasPrincipalKey(e => new { e.EmployeeId, e.ValidPeriod }) - .HasPeriod(); + .WithPeriod(); }); } ``` @@ -133,6 +133,16 @@ INSERT INTO project_assignments (employee_id, project_name, assignment_period) VALUES (1, 'Legacy Project', tstzrange('2022-01-01', '2022-06-01', '[)')); ``` +## NodaTime ranges + +With the [NodaTime plugin](../mapping/nodatime.md) enabled, temporal constraints also support `Interval` (mapped to `tstzrange`) and `DateInterval` (mapped to `daterange`). For example, the employee's validity period can be declared as: + +```csharp +public Interval ValidPeriod { get; set; } +``` + +Configure the key with `.WithoutOverlaps()` and the foreign key with `.WithPeriod()` as above; both sides of the relationship must use compatible range mappings. The range property must be last in both keys. + ## Querying temporal data When querying temporal data, PostgreSQL's range operators are particularly useful. The containment operator (`@>`) checks if a range contains a specific point in time: diff --git a/docs/modeling/concurrency.md b/docs/modeling/concurrency.md index afe8dd9ee8..7129f07f47 100644 --- a/docs/modeling/concurrency.md +++ b/docs/modeling/concurrency.md @@ -46,3 +46,9 @@ public class SomeEntity ``` *** + +## Database concurrency failures + +Starting with version 11.0, PostgreSQL serialization failures (`40001`) and deadlocks (`40P01`) during `SaveChanges()` or `SaveChangesAsync()` are reported as `DbUpdateConcurrencyException`, with the original `PostgresException` as the inner exception. This also covers failures during the automatic transaction commit performed by `SaveChanges`. An explicit application call to commit a transaction is not covered by this conversion. + +As with other concurrency failures, the application must decide whether and how to retry the operation. See the [EF Core concurrency documentation](https://learn.microsoft.com/ef/core/saving/concurrency#resolving-concurrency-conflicts) and [execution strategies](../misc/other.md#execution-strategy). diff --git a/docs/modeling/generated-properties.md b/docs/modeling/generated-properties.md index f0c43ad8c0..b480ebae1f 100644 --- a/docs/modeling/generated-properties.md +++ b/docs/modeling/generated-properties.md @@ -27,6 +27,15 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) => modelBuilder.UseIdentityByDefaultColumns(); ``` +Starting with version 11.0, you can disable the default PostgreSQL value generation strategy for the entire model: + +```csharp +protected override void OnModelCreating(ModelBuilder modelBuilder) + => modelBuilder.UseNoIdentityGeneration(); +``` + +Explicitly configured property strategies are unaffected. This does not disable EF value generation or remove database defaults or computed expressions; use `ValueGeneratedNever()` to disable value generation for an individual property. + ### Defining the strategy for a single property Regardless of the model default, you can define a value-generation strategy on a property-by-property basis: diff --git a/docs/release-notes/11.0.md b/docs/release-notes/11.0.md index e8321e2e61..72a8adb35a 100644 --- a/docs/release-notes/11.0.md +++ b/docs/release-notes/11.0.md @@ -9,6 +9,16 @@ EF 11 complex types mapped with `ToJson()` now support indexing JSON members thr > [!NOTE] > The provider currently references EF `11.0.0-rc.2.26504.105`, which has two temporary limitations: C# migration scaffolding for JSON member indexes fails because it cannot scaffold a `RelationalJsonIndex` literal, and composite member indexes with mixed ascending/descending directions fail before SQL generation. Uniform ascending or descending composites can generate SQL, but remain affected by the scaffolding limitation. Both issues are fixed in [dotnet/efcore#39089](https://github.com/dotnet/efcore/pull/39089); the provider has not yet consumed those fixes. +## PostgreSQL JSON functions with ToJson + +The existing PostgreSQL JSON functions, such as `EF.Functions.JsonContains()` and `EF.Functions.JsonExists()`, can now be used with complex types and owned entities mapped with `ToJson()`, including nested objects and collections: + +```csharp +var customers = await context.Customers + .Where(c => EF.Functions.JsonContains(c.Details, """{"Name": "Joe"}""")) + .ToListAsync(); +``` + ## Support for PostgreSQL 18 temporal constraints PostgreSQL 18 introduced powerful temporal constraints that allow enforcing data integrity over time periods directly at the database level. The EF Core provider now supports these features, allowing you to define temporal primary keys, unique constraints, and foreign keys. @@ -37,7 +47,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) .HasDefaultValueSql("tstzrange(now(), 'infinity', '[)')"); b.HasKey(e => new { e.EmployeeId, e.ValidPeriod }) - .HasWithoutOverlaps(); + .WithoutOverlaps(); }); } ``` @@ -78,7 +88,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) .WithMany() .HasForeignKey(e => new { e.EmployeeId, e.AssignmentPeriod }) .HasPrincipalKey(e => new { e.EmployeeId, e.ValidPeriod }) - .HasPeriod(); + .WithPeriod(); }); } ``` @@ -92,17 +102,46 @@ FOREIGN KEY (employee_id, PERIOD assignment_period) REFERENCES employees (employee_id, PERIOD valid_period); ``` -For more details, see the [temporal constraints documentation](../misc/temporal-constraints.md). +Temporal constraints also support NodaTime `Interval` and `DateInterval` properties when the NodaTime plugin is enabled. For more details, see the [temporal constraints documentation](../misc/temporal-constraints.md). ## Other new features +* Added [`EF.Functions.DateTrunc()`](../mapping/translations.md#date-and-time-functions) for truncating date/time values to units such as hours, days or months, with support for [NodaTime types](../mapping/nodatime.md#operation-translation) and an optional time zone for `timestamp with time zone` values ([#3831](https://github.com/npgsql/efcore.pg/issues/3831)). * Added `EF.Functions.IntersectsBbox(geom1, geom2)` for expressing [the PostGIS `&&` operator](https://postgis.net/docs/geometry_overlaps.html). Thanks to [@bjornharrtell](https://github.com/bjornharrtell) for this contribution! +* Added [`EF.Functions.JsonPathExists()`](../mapping/translations.md#json-functions), translated to `JSON_EXISTS()` on PostgreSQL 17 and above ([#3733](https://github.com/npgsql/efcore.pg/issues/3733)). +* Added [`EF.Functions.FuzzyStringMatchDaitchMokotoff()`](../mapping/translations.md#fuzzy-string-match-functions) for Daitch-Mokotoff phonetic matching with the `fuzzystrmatch` extension on PostgreSQL 16 and above ([#3524](https://github.com/npgsql/efcore.pg/issues/3524)). +* Added [`ModelBuilder.UseNoIdentityGeneration()`](../modeling/generated-properties.md#defining-the-default-strategy-for-the-entire-model) to disable the model's default PostgreSQL identity generation strategy ([#3723](https://github.com/npgsql/efcore.pg/issues/3723)). +* [Covering indexes](../modeling/indexes.md#covering-indexes-include) now support including properties nested within complex types mapped to regular columns. +* Indexes configured with [`IsCreatedConcurrently()`](../modeling/indexes.md#creating-indexes-concurrently) are now also dropped concurrently when removed by migrations ([#3901](https://github.com/npgsql/efcore.pg/issues/3901)). +* Added translation for the [three-argument `TimeZoneInfo.ConvertTimeBySystemTimeZoneId()` overload](../mapping/translations.md#date-and-time-functions), converting between source and destination time zones for `timestamp without time zone` values ([#3938](https://github.com/npgsql/efcore.pg/issues/3938)). +* Added translations for the `char` overloads of `string.IndexOf()`, `Replace()`, `StartsWith()`, `EndsWith()` and `Contains()` ([#3547](https://github.com/npgsql/efcore.pg/issues/3547)). +* Added translations for single-argument `Parse(string)` calls on `bool`, `byte`, `short`, `int`, `long`, `float`, `double` and `decimal`. +* Array `SequenceEqual()` now supports slices produced by `Skip()` and `Take()` ([#3633](https://github.com/npgsql/efcore.pg/issues/3633)). `Intersect().Any()` over static readonly collections with non-null elements can now use PostgreSQL's array overlap operator ([#3638](https://github.com/npgsql/efcore.pg/issues/3638)). +* `Any()` on `byte[]` properties mapped to `bytea` is now translated to a length check. +* [Creating PostgreSQL extensions](../misc/other.md#postgresql-extensions) now uses `CASCADE` to install their dependencies automatically ([#3682](https://github.com/npgsql/efcore.pg/issues/3682)). +* Support specifying the encoding of newly created PostgreSQL databases with `ModelBuilder.UseDatabaseEncoding()` ([#3526](https://github.com/npgsql/efcore.pg/issues/3526)). + +See the [11.0.0 milestone](https://github.com/npgsql/efcore.pg/milestone/75?closed=1) for the full list of issues. ## Breaking changes -* The provider now assumes at least PostgreSQL 16 by default, taking advantage of newer features (previously, PostgreSQL 14 was targeted). You can configure the targeted PostgreSQL version when configuring your context: +### PostgreSQL 16 is targeted by default + +The provider now assumes at least PostgreSQL 16 by default, taking advantage of newer features (previously, PostgreSQL 14 was targeted). You can configure the targeted PostgreSQL version when configuring your context: ```c# protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) => optionsBuilder.UseNpgsql("", o => o.SetPostgresVersion(14, 0)); ``` + +### Changes to transient and concurrency exceptions + +The default, non-retrying execution strategy no longer wraps transient failures in an additional `InvalidOperationException`. Applications catching that wrapper should instead handle the underlying exception. + +In addition, PostgreSQL serialization failures (`40001`) and deadlocks (`40P01`) during `SaveChanges()` or `SaveChangesAsync()` now throw `DbUpdateConcurrencyException`, with the original `PostgresException` as the inner exception. This includes failures during an automatically committed transaction, but not a transaction committed explicitly by the application. Previously, these failures were generally exposed as `DbUpdateException` wrapped in `InvalidOperationException`. + +These changes do not enable automatic retries. See [execution strategies](../misc/other.md#execution-strategy) and [database concurrency failures](../modeling/concurrency.md#database-concurrency-failures) for details ([#3098](https://github.com/npgsql/efcore.pg/issues/3098)). + +### Initial migration rollback removes model-level objects + +The `Down()` method of newly scaffolded initial migrations now removes model-level enum, range and collation definitions that were previously left behind. Review the generated operations if these objects are shared with other applications ([#3604](https://github.com/npgsql/efcore.pg/issues/3604)). From a9b12ba5fdc0327fcf26429ff5f24223737f60ae Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Thu, 29 Oct 2026 12:12:08 +0100 Subject: [PATCH 199/207] Document EFCore.PG 11.0 improvements and translations (#476) Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: b4f6a4da-cf90-40f2-a1e2-2a54035bd9df --- docs/mapping/nodatime.md | 1 + docs/mapping/nts.md | 5 +++ docs/mapping/translations.md | 31 +++++++++++++++++ docs/release-notes/11.0.md | 67 ++++++++++++++++++++++++++++++------ 4 files changed, 94 insertions(+), 10 deletions(-) diff --git a/docs/mapping/nodatime.md b/docs/mapping/nodatime.md index a24c1542c4..d17b8ef461 100644 --- a/docs/mapping/nodatime.md +++ b/docs/mapping/nodatime.md @@ -131,6 +131,7 @@ LocalDateTime.InZoneLeniently(DateTimeZoneProviders.Tzdb["Europe/Berlin"]).ToIns ZonedDateTime.ToInstant | No PG operation (.NET-side conversion from ZonedDateTime to Instant only) | Instant.InUtc | No PG operation (.NET-side conversion from Instant to ZonedDateTime only) | Instant.ToDateTimeUtc | No PG operation (.NET-side conversion from Instant to UTC DateTime only) | +LocalDateTime.ToDateTimeUnspecified() | No PG operation (timestamp without time zone is unchanged) | Added in 11.0 EF.Functions.Sum(periods) | [sum(periods)](https://www.postgresql.org/docs/current/functions-aggregate.html#FUNCTIONS-AGGREGATE-TABLE) | See [Aggregate functions](translations.md#aggregate-functions). EF.Functions.Sum(durations) | [sum(durations)](https://www.postgresql.org/docs/current/functions-aggregate.html#FUNCTIONS-AGGREGATE-TABLE) | See [Aggregate functions](translations.md#aggregate-functions). EF.Functions.Average(periods) | [avg(durations)](https://www.postgresql.org/docs/current/functions-aggregate.html#FUNCTIONS-AGGREGATE-TABLE) | See [Aggregate functions](translations.md#aggregate-functions). diff --git a/docs/mapping/nts.md b/docs/mapping/nts.md index 3ae651f52c..57401136c5 100644 --- a/docs/mapping/nts.md +++ b/docs/mapping/nts.md @@ -162,6 +162,8 @@ EF.Functions.IsWithinDistance(geom1, geom2, d, useSpheriod) | [ST_DWithin(g geom.IsSimple() | [ST_IsSimple(geom)](https://postgis.net/docs/ST_IsSimple.html) geom.IsValid() | [ST_IsValid(geom)](https://postgis.net/docs/ST_IsValid.html) lineString.Length | [ST_Length(lineString)](https://postgis.net/docs/ST_Length.html) +EF.Functions.LineInterpolatePoint(lineString, fraction) | [ST_LineInterpolatePoint(lineString, fraction)](https://postgis.net/docs/ST_LineInterpolatePoint.html) | Added in 11.0 +EF.Functions.LineMerge(geom) | [ST_LineMerge(geom)](https://postgis.net/docs/ST_LineMerge.html) | Added in 11.0 geom.Normalized | [ST_Normalize(geom)](https://postgis.net/docs/ST_Normalize.html) geomCollection.NumGeometries | [ST_NumGeometries(geomCollection)](https://postgis.net/docs/ST_NumGeometries.html) polygon.NumInteriorRings | [ST_NumInteriorRings(polygon)](https://postgis.net/docs/ST_NumInteriorRings.html) @@ -170,6 +172,9 @@ geom1.Overlaps(geom2) | [ST_Overlaps( geom.PointOnSurface | [ST_PointOnSurface(geom)](https://postgis.net/docs/ST_PointOnSurface.html) geom1.Relate(geom2) | [ST_Relate(geom1, geom2)](https://postgis.net/docs/ST_Relate.html) geom.Reverse() | [ST_Reverse(geom)](https://postgis.net/docs/ST_Reverse.html) +EF.Functions.Scale(geom, xFactor, yFactor) | [ST_Scale(geom, xFactor, yFactor)](https://postgis.net/docs/ST_Scale.html) | Added in 11.0 +EF.Functions.Scale(geom, xFactor, yFactor, zFactor) | [ST_Scale(geom, xFactor, yFactor, zFactor)](https://postgis.net/docs/ST_Scale.html) | Added in 11.0 +EF.Functions.SetSrid(geom, srid) | [ST_SetSRID(geom, srid)](https://postgis.net/docs/ST_SetSRID.html) | Added in 11.0 geom1.SRID | [ST_SRID(geom1)](https://postgis.net/docs/ST_SRID.html) lineString.StartPoint | [ST_StartPoint(lineString)](https://postgis.net/docs/ST_StartPoint.html) geom1.SymmetricDifference(geom2) | [ST_SymDifference(geom1, geom2)](https://postgis.net/docs/ST_SymDifference.html) diff --git a/docs/mapping/translations.md b/docs/mapping/translations.md index 2d0151be9b..366677d900 100644 --- a/docs/mapping/translations.md +++ b/docs/mapping/translations.md @@ -32,6 +32,7 @@ stringValue.Replace(oldValue, newValue) | replace(stringVa stringValue.StartsWith(value) | stringValue LIKE value \|\| '%' | char overload added in 11.0 stringValue.Substring(startIndex, length) | substr(stringValue, startIndex + 1, @length) stringValue.ToLower() | lower(stringValue) +stringValue.ToString() | stringValue | Null values remain null stringValue.ToUpper() | upper(stringValue) stringValue.Trim() | btrim(stringValue) stringValue.Trim(trimChar) | btrim(stringValue, trimChar) @@ -71,6 +72,8 @@ EF.Functions.DateTrunc("month", value) | [date_trunc( EF.Functions.DateTrunc("month", utcDateTime, "Europe/Berlin") | [date_trunc('month', utcDateTime, 'Europe/Berlin')](https://www.postgresql.org/docs/current/functions-datetime.html) | Added in 11.0; timestamp with time zone only dateTime.AddDays(1) | [dateTime + INTERVAL '1 days'](https://www.postgresql.org/docs/current/functions-datetime.html#OPERATORS-DATETIME-TABLE) | dateTime.AddHours(value) | [dateTime + INTERVAL '1 hours'](https://www.postgresql.org/docs/current/functions-datetime.html#OPERATORS-DATETIME-TABLE) | +dateTime.AddMilliseconds(value) (also DateTimeOffset) | [dateTime + value * INTERVAL '1 milliseconds'](https://www.postgresql.org/docs/current/functions-datetime.html#OPERATORS-DATETIME-TABLE) | Added in 11.0 +dateTime.AddMicroseconds(value) (also DateTimeOffset) | [dateTime + value * INTERVAL '1 microseconds'](https://www.postgresql.org/docs/current/functions-datetime.html#OPERATORS-DATETIME-TABLE) | Added in 11.0 dateTime.AddMinutes(1) | [dateTime + INTERVAL '1 minutes'](https://www.postgresql.org/docs/current/functions-datetime.html#OPERATORS-DATETIME-TABLE) | dateTime.AddMonths(1) | [dateTime + INTERVAL '1 months'](https://www.postgresql.org/docs/current/functions-datetime.html#OPERATORS-DATETIME-TABLE) | dateTime.AddSeconds(1) | [dateTime + INTERVAL '1 seconds'](https://www.postgresql.org/docs/current/functions-datetime.html#OPERATORS-DATETIME-TABLE) | @@ -80,6 +83,8 @@ dateTime.Day | [date_part(' dateTime.DayOfWeek | [floor(date_part('dow', dateTime))::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | dateTime.DayOfYear | [date_part('doy', dateTime)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | dateTime.Hour | [date_part('hour', dateTime)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | +dateTime.Millisecond (also DateTimeOffset, TimeOnly) | [floor(date_part('milliseconds', dateTime))::INT % 1000](https://www.postgresql.org/docs/current/functions-datetime.html) | Added in 11.0 +dateTime.Microsecond (also DateTimeOffset, TimeOnly) | [date_part('microseconds', dateTime)::INT % 1000](https://www.postgresql.org/docs/current/functions-datetime.html) | Added in 11.0 dateTime.Minute | [date_part('minute', dateTime)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | dateTime.Month | [date_part('month', dateTime)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | dateTime.Second | [date_part('second', dateTime)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | @@ -129,6 +134,29 @@ EF.Functions.JsonExistAll(json, key1, key2) | json ?& ARRAY[key1, key2] EF.Functions.JsonTypeof(json) | jsonb_typeof(json) or json_typeof(json) | Selected according to the mapped column type EF.Functions.JsonPathExists(json, "$.Age") | JSON_EXISTS(json, '$.Age') | Added in 11.0; requires PostgreSQL 17 or above +## Hstore translations + +The following operations are supported for `Dictionary` and `ImmutableDictionary` mapped to PostgreSQL [`hstore`](https://www.postgresql.org/docs/current/hstore.html). Operations shown with `immutableDictionary` apply only to `ImmutableDictionary`. + +| .NET | SQL | Notes | +| ---- | --- | ----- | +| dictionary[key] | dictionary -> key | Added in 11.0 | +| dictionary.GetValueOrDefault(key) | dictionary -> key | Added in 11.0 | +| dictionary.GetValueOrDefault(key, fallback) | CASE WHEN dictionary ? key THEN dictionary -> key ELSE fallback END | Added in 11.0 | +| dictionary.ContainsKey(key) | dictionary ? key | Added in 11.0 | +| dictionary.ContainsValue(value) | array_position(avals(dictionary), value) IS NOT NULL | Added in 11.0 | +| dictionary.Count | cardinality(akeys(dictionary)) | Added in 11.0 | +| immutableDictionary.IsEmpty | cardinality(akeys(immutableDictionary)) = 0 | Added in 11.0 | +| immutableDictionary.Remove(key) | immutableDictionary - key | Added in 11.0 | +| immutableDictionary.RemoveRange(keys) | immutableDictionary - keys | Added in 11.0 | +| immutableDictionary.SetItems(otherDictionary) | immutableDictionary \|\| otherDictionary | Added in 11.0 | +| keys.All(key => dictionary.ContainsKey(key)) | dictionary ?& keys | Added in 11.0 | +| keys.Any(key => dictionary.ContainsKey(key)) | dictionary ?\| keys | Added in 11.0 | + +Lookups return SQL `NULL` for missing keys, stored NULL values and NULL hstores, rather than throwing for a missing key. The explicit `GetValueOrDefault` fallback distinguishes a missing key from a key whose stored value is NULL. Key existence and counts include stored-NULL entries, and `ContainsValue(null)` finds stored NULL values. + +`SetItems` accepts another hstore-mapped mutable or immutable dictionary, not arbitrary sequences of key/value pairs. + ## Miscellaneous functions .NET | SQL | Notes @@ -155,8 +183,11 @@ decimal.Parse(stringValue) | CAST(stringValue AS numeric) | Added bytes[i] | get_byte(bytes, i) | bytes.Contains(value) | position(value IN bytes) > 0 | bytes.Any() | length(bytes) > 0 | Added in 11.0 +bytes.Concat(bytes2) | bytes \|\| bytes2 | Added in 11.0 bytes.Length | length(@bytes) | bytes1.SequenceEqual(bytes2) | @bytes = @second | +bitArray.Get(index) | get_bit(bitArray, index) = 1 | Added in 11.0 +bitArray[index] | get_bit(bitArray, index) = 1 | Added in 11.0 ## Math functions diff --git a/docs/release-notes/11.0.md b/docs/release-notes/11.0.md index 72a8adb35a..60f97b3998 100644 --- a/docs/release-notes/11.0.md +++ b/docs/release-notes/11.0.md @@ -104,22 +104,65 @@ REFERENCES employees (employee_id, PERIOD valid_period); Temporal constraints also support NodaTime `Interval` and `DateInterval` properties when the NodaTime plugin is enabled. For more details, see the [temporal constraints documentation](../misc/temporal-constraints.md). +## New translations + +EFCore.PG 11 brings many new query translations across the board: + +| .NET | SQL | Notes | +| ---- | --- | ----- | +| [EF.Functions.DateTrunc("month", value)](../mapping/translations.md#date-and-time-functions) | date_trunc('month', value) | Also supports [NodaTime types](../mapping/nodatime.md#operation-translation) and an optional time zone for timestamptz ([#3831](https://github.com/npgsql/efcore.pg/issues/3831)). | +| [EF.Functions.JsonPathExists(json, "$.Age")](../mapping/translations.md#json-functions) | JSON_EXISTS(json, '$.Age') | PostgreSQL 17+ ([#3733](https://github.com/npgsql/efcore.pg/issues/3733)). | +| [EF.Functions.FuzzyStringMatchDaitchMokotoff(text)](../mapping/translations.md#fuzzy-string-match-functions) | daitch_mokotoff(text) | Requires fuzzystrmatch on PostgreSQL 16+ ([#3524](https://github.com/npgsql/efcore.pg/issues/3524)). | +| [TimeZoneInfo.ConvertTimeBySystemTimeZoneId(dateTime, sourceTimeZoneId, destinationTimeZoneId)](../mapping/translations.md#date-and-time-functions) | (dateTime AT TIME ZONE sourceTimeZoneId) AT TIME ZONE destinationTimeZoneId | timestamp without time zone ([#3938](https://github.com/npgsql/efcore.pg/issues/3938)). | +| [dateTime.Millisecond](../mapping/translations.md#date-and-time-functions) | floor(date_part('milliseconds', dateTime))::INT % 1000 | Also DateTimeOffset, TimeOnly ([#3406](https://github.com/npgsql/efcore.pg/issues/3406)). | +| [dateTime.Microsecond](../mapping/translations.md#date-and-time-functions) | date_part('microseconds', dateTime)::INT % 1000 | Also DateTimeOffset, TimeOnly ([#3406](https://github.com/npgsql/efcore.pg/issues/3406)). | +| [dateTime.AddMilliseconds(value)](../mapping/translations.md#date-and-time-functions) | dateTime + value * INTERVAL '1 milliseconds' | Also DateTimeOffset ([#3449](https://github.com/npgsql/efcore.pg/issues/3449)). | +| [dateTime.AddMicroseconds(value)](../mapping/translations.md#date-and-time-functions) | dateTime + value * INTERVAL '1 microseconds' | Also DateTimeOffset ([#3449](https://github.com/npgsql/efcore.pg/issues/3449)). | +| [LocalDateTime.ToDateTimeUnspecified()](../mapping/nodatime.md#operation-translation) | No PG operation | NodaTime ([#4048](https://github.com/npgsql/efcore.pg/issues/4048)). | +| stringValue.IndexOf(value) | strpos(stringValue, value) - 1 | char overload ([#3547](https://github.com/npgsql/efcore.pg/issues/3547)). | +| stringValue.Replace(oldValue, newValue) | replace(stringValue, oldValue, newValue) | char overload | +| stringValue.StartsWith(value) | stringValue LIKE value \|\| '%' | char overload | +| stringValue.EndsWith(value) | stringValue LIKE '%' \|\| value | char overload | +| stringValue.Contains(value) | stringValue LIKE %value% | char overload | +| int.Parse(stringValue) | CAST(stringValue AS integer) | Also bool, byte, short, long, float, double and decimal | +| [array1.Take(2).SequenceEqual(array2)](../mapping/array.md#operation-translation) | array1\[:2\] = array2 | Also Skip() and Skip().Take() ([#3633](https://github.com/npgsql/efcore.pg/issues/3633)). | +| [array1.Intersect(array2).Any()](../mapping/array.md#operation-translation) | array1 && array2 | Now supports static readonly collections with non-null elements ([#3638](https://github.com/npgsql/efcore.pg/issues/3638)). | +| [bytes.Any()](../mapping/translations.md#binary-functions) | length(bytes) > 0 | byte[] mapped to bytea | +| [bytes.Concat(bytes2)](../mapping/translations.md#binary-functions) | bytes \|\| bytes2 | byte[] columns mapped to bytea ([#2200](https://github.com/npgsql/efcore.pg/pull/2200)). | +| [bitArray.Get(index)](../mapping/translations.md#binary-functions) | get_bit(bitArray, index) = 1 | Also bitArray[index] ([#2836](https://github.com/npgsql/efcore.pg/issues/2836)). | +| [EF.Functions.IntersectsBbox(geom1, geom2)](../mapping/nts.md#operation-translation) | [geom1 && geom2](https://postgis.net/docs/geometry_overlaps.html) | Thanks to [@bjornharrtell](https://github.com/bjornharrtell)! | +| [EF.Functions.LineInterpolatePoint(lineString, fraction)](../mapping/nts.md#operation-translation) | [ST_LineInterpolatePoint(lineString, fraction)](https://postgis.net/docs/ST_LineInterpolatePoint.html) | [#2632](https://github.com/npgsql/efcore.pg/issues/2632) | +| [EF.Functions.LineMerge(geom)](../mapping/nts.md#operation-translation) | [ST_LineMerge(geom)](https://postgis.net/docs/ST_LineMerge.html) | [#2632](https://github.com/npgsql/efcore.pg/issues/2632) | +| [EF.Functions.Scale(geom, xFactor, yFactor)](../mapping/nts.md#operation-translation) | [ST_Scale(geom, xFactor, yFactor)](https://postgis.net/docs/ST_Scale.html) | Also supports a zFactor; scales relative to the coordinate origin ([#829](https://github.com/npgsql/efcore.pg/issues/829)). | +| [EF.Functions.SetSrid(geom, srid)](../mapping/nts.md#operation-translation) | [ST_SetSRID(geom, srid)](https://postgis.net/docs/ST_SetSRID.html) | Sets SRID metadata without changing coordinates; use Transform for reprojection ([#3245](https://github.com/npgsql/efcore.pg/issues/3245)). | + +The following [hstore translations](../mapping/translations.md#hstore-translations) are now supported for `Dictionary` and `ImmutableDictionary`, with additional operations specific to immutable dictionaries ([#4082](https://github.com/npgsql/efcore.pg/pull/4082)): + +| .NET | SQL | Notes | +| ---- | --- | ----- | +| dictionary[key] | dictionary -> key | Added in 11.0 | +| dictionary.GetValueOrDefault(key) | dictionary -> key | Added in 11.0 | +| dictionary.GetValueOrDefault(key, fallback) | CASE WHEN dictionary ? key THEN dictionary -> key ELSE fallback END | Added in 11.0 | +| dictionary.ContainsKey(key) | dictionary ? key | Added in 11.0 | +| dictionary.ContainsValue(value) | array_position(avals(dictionary), value) IS NOT NULL | Added in 11.0 | +| dictionary.Count | cardinality(akeys(dictionary)) | Added in 11.0 | +| immutableDictionary.IsEmpty | cardinality(akeys(immutableDictionary)) = 0 | Added in 11.0 | +| immutableDictionary.Remove(key) | immutableDictionary - key | Added in 11.0 | +| immutableDictionary.RemoveRange(keys) | immutableDictionary - keys | Added in 11.0 | +| immutableDictionary.SetItems(otherDictionary) | immutableDictionary \|\| otherDictionary | Added in 11.0 | +| keys.All(key => dictionary.ContainsKey(key)) | dictionary ?& keys | Added in 11.0 | +| keys.Any(key => dictionary.ContainsKey(key)) | dictionary ?\| keys | Added in 11.0 | + ## Other new features -* Added [`EF.Functions.DateTrunc()`](../mapping/translations.md#date-and-time-functions) for truncating date/time values to units such as hours, days or months, with support for [NodaTime types](../mapping/nodatime.md#operation-translation) and an optional time zone for `timestamp with time zone` values ([#3831](https://github.com/npgsql/efcore.pg/issues/3831)). -* Added `EF.Functions.IntersectsBbox(geom1, geom2)` for expressing [the PostGIS `&&` operator](https://postgis.net/docs/geometry_overlaps.html). Thanks to [@bjornharrtell](https://github.com/bjornharrtell) for this contribution! -* Added [`EF.Functions.JsonPathExists()`](../mapping/translations.md#json-functions), translated to `JSON_EXISTS()` on PostgreSQL 17 and above ([#3733](https://github.com/npgsql/efcore.pg/issues/3733)). -* Added [`EF.Functions.FuzzyStringMatchDaitchMokotoff()`](../mapping/translations.md#fuzzy-string-match-functions) for Daitch-Mokotoff phonetic matching with the `fuzzystrmatch` extension on PostgreSQL 16 and above ([#3524](https://github.com/npgsql/efcore.pg/issues/3524)). +* [Generated `tsvector` columns and full-text expression indexes](../mapping/full-text-search.md#setting-up-and-querying-a-full-text-search-index-on-an-entity) now support integer and exact-numeric inputs by casting them to text ([#2615](https://github.com/npgsql/efcore.pg/issues/2615)). +* [`MapEnum`](../mapping/enum.md) now respects type-level `[PgName]` attributes when no PostgreSQL enum name is supplied ([#3379](https://github.com/npgsql/efcore.pg/issues/3379)). * Added [`ModelBuilder.UseNoIdentityGeneration()`](../modeling/generated-properties.md#defining-the-default-strategy-for-the-entire-model) to disable the model's default PostgreSQL identity generation strategy ([#3723](https://github.com/npgsql/efcore.pg/issues/3723)). * [Covering indexes](../modeling/indexes.md#covering-indexes-include) now support including properties nested within complex types mapped to regular columns. * Indexes configured with [`IsCreatedConcurrently()`](../modeling/indexes.md#creating-indexes-concurrently) are now also dropped concurrently when removed by migrations ([#3901](https://github.com/npgsql/efcore.pg/issues/3901)). -* Added translation for the [three-argument `TimeZoneInfo.ConvertTimeBySystemTimeZoneId()` overload](../mapping/translations.md#date-and-time-functions), converting between source and destination time zones for `timestamp without time zone` values ([#3938](https://github.com/npgsql/efcore.pg/issues/3938)). -* Added translations for the `char` overloads of `string.IndexOf()`, `Replace()`, `StartsWith()`, `EndsWith()` and `Contains()` ([#3547](https://github.com/npgsql/efcore.pg/issues/3547)). -* Added translations for single-argument `Parse(string)` calls on `bool`, `byte`, `short`, `int`, `long`, `float`, `double` and `decimal`. -* Array `SequenceEqual()` now supports slices produced by `Skip()` and `Take()` ([#3633](https://github.com/npgsql/efcore.pg/issues/3633)). `Intersect().Any()` over static readonly collections with non-null elements can now use PostgreSQL's array overlap operator ([#3638](https://github.com/npgsql/efcore.pg/issues/3638)). -* `Any()` on `byte[]` properties mapped to `bytea` is now translated to a length check. * [Creating PostgreSQL extensions](../misc/other.md#postgresql-extensions) now uses `CASCADE` to install their dependencies automatically ([#3682](https://github.com/npgsql/efcore.pg/issues/3682)). * Support specifying the encoding of newly created PostgreSQL databases with `ModelBuilder.UseDatabaseEncoding()` ([#3526](https://github.com/npgsql/efcore.pg/issues/3526)). +* Custom collation references now respect the model's default schema and correctly handle dots in collation and schema names across migrations, queries and scaffolding ([#4072](https://github.com/npgsql/efcore.pg/pull/4072)). See the [11.0.0 milestone](https://github.com/npgsql/efcore.pg/milestone/75?closed=1) for the full list of issues. @@ -144,4 +187,8 @@ These changes do not enable automatic retries. See [execution strategies](../mis ### Initial migration rollback removes model-level objects -The `Down()` method of newly scaffolded initial migrations now removes model-level enum, range and collation definitions that were previously left behind. Review the generated operations if these objects are shared with other applications ([#3604](https://github.com/npgsql/efcore.pg/issues/3604)). +Rolling back a newly scaffolded initial migration now drops enum, range and collation definitions that were previously left behind. If other applications use these objects, the rollback can fail due to their dependencies; remove the corresponding drop operations from `Down()` if the objects must be preserved ([#3604](https://github.com/npgsql/efcore.pg/issues/3604)). + +### Collation annotations containing literal double quotes + +Previously scaffolded snapshots and migrations with raw collation annotation keys containing literal double quotes in collation or schema names can be misinterpreted by the new identifier encoding. They may fail to decode or reference the wrong collation; update affected annotation keys manually before using them with 11.0 ([#4072](https://github.com/npgsql/efcore.pg/pull/4072)). From ea021c76c23203aadec2c8c9a025d20b2b68be23 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Fri, 20 Nov 2026 16:06:28 +0100 Subject: [PATCH 200/207] Update documentation for Npgsql 11.0 and EFCore.PG 11.0 (#481) --- docs/release-notes/11.0.md | 3 --- 1 file changed, 3 deletions(-) diff --git a/docs/release-notes/11.0.md b/docs/release-notes/11.0.md index 60f97b3998..28397b0ada 100644 --- a/docs/release-notes/11.0.md +++ b/docs/release-notes/11.0.md @@ -6,9 +6,6 @@ Npgsql.EntityFrameworkCore.PostgreSQL version 11.0 is currently in development. EF 11 complex types mapped with `ToJson()` now support indexing JSON members through the existing `HasIndex` APIs, including unique and composite indexes. By default, these create B-tree expression indexes over the selected values; explicit GIN indexes can target `jsonb` arrays and subdocuments. See [Indexing JSON columns](../mapping/json.md#indexing-json-columns) for examples and limitations. -> [!NOTE] -> The provider currently references EF `11.0.0-rc.2.26504.105`, which has two temporary limitations: C# migration scaffolding for JSON member indexes fails because it cannot scaffold a `RelationalJsonIndex` literal, and composite member indexes with mixed ascending/descending directions fail before SQL generation. Uniform ascending or descending composites can generate SQL, but remain affected by the scaffolding limitation. Both issues are fixed in [dotnet/efcore#39089](https://github.com/dotnet/efcore/pull/39089); the provider has not yet consumed those fixes. - ## PostgreSQL JSON functions with ToJson The existing PostgreSQL JSON functions, such as `EF.Functions.JsonContains()` and `EF.Functions.JsonExists()`, can now be used with complex types and owned entities mapped with `ToJson()`, including nested objects and collections: From 76a9d6d1258c140644d6db1583eb4d964914d74a Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Fri, 20 Nov 2026 16:21:35 +0100 Subject: [PATCH 201/207] Finalize the EFCore.PG 11.0 release notes (#482) --- docs/release-notes/11.0.md | 6 +++++- docs/toc.yml | 2 +- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/docs/release-notes/11.0.md b/docs/release-notes/11.0.md index 28397b0ada..9ec1c68c7d 100644 --- a/docs/release-notes/11.0.md +++ b/docs/release-notes/11.0.md @@ -1,6 +1,6 @@ # 11.0 Release Notes -Npgsql.EntityFrameworkCore.PostgreSQL version 11.0 is currently in development. Previews are available on [nuget.org](https://www.nuget.org/packages/Npgsql.EntityFrameworkCore.PostgreSQL). +Npgsql.EntityFrameworkCore.PostgreSQL 11.0.0 is available on [NuGet](https://www.nuget.org/packages/Npgsql.EntityFrameworkCore.PostgreSQL/11.0.0). ## Indexes over JSON members @@ -165,6 +165,10 @@ See the [11.0.0 milestone](https://github.com/npgsql/efcore.pg/milestone/75?clos ## Breaking changes +### The dependency injection extension class was renamed + +The provider's `NpgsqlServiceCollectionExtensions` class was renamed to `NpgsqlEntityFrameworkServiceCollectionExtensions` to avoid a name collision with the Npgsql driver. Extension-method calls such as `services.AddNpgsql(...)` and `services.AddEntityFrameworkNpgsql()` don't need source changes, but assemblies compiled against the old methods must be rebuilt. If your code references the class directly, update it to use the new name ([npgsql/efcore.pg#4139](https://github.com/npgsql/efcore.pg/pull/4139)). + ### PostgreSQL 16 is targeted by default The provider now assumes at least PostgreSQL 16 by default, taking advantage of newer features (previously, PostgreSQL 14 was targeted). You can configure the targeted PostgreSQL version when configuring your context: diff --git a/docs/toc.yml b/docs/toc.yml index 1c4988380e..484d40cbe5 100644 --- a/docs/toc.yml +++ b/docs/toc.yml @@ -2,7 +2,7 @@ href: index.md - name: Release notes items: - - name: "11.0 (preview)" + - name: "11.0" href: release-notes/11.0.md - name: "10.0" href: release-notes/10.0.md From 3bacff44e62057f21eb6bddc5fa60254a1865220 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Wed, 25 Nov 2026 13:55:04 +0100 Subject: [PATCH 202/207] Document EF Core vector search (#484) Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- docs/mapping/vector-search.md | 91 +++++++++++++++++++++++++++++++++++ docs/toc.yml | 2 + 2 files changed, 93 insertions(+) create mode 100644 docs/mapping/vector-search.md diff --git a/docs/mapping/vector-search.md b/docs/mapping/vector-search.md new file mode 100644 index 0000000000..7094fea72f --- /dev/null +++ b/docs/mapping/vector-search.md @@ -0,0 +1,91 @@ +# Vector Search + +Vector search finds items whose vectors are close to a query vector. For example, an embedding model can represent text or images as vectors, allowing a search to find semantically similar items rather than just matching keywords. The query vector and stored vectors must be produced by the same embedding model. + +PostgreSQL supports vector search through the [pgvector extension](https://github.com/pgvector/pgvector). The [pgvector .NET library](https://github.com/pgvector/pgvector-dotnet#entity-framework-core) provides EF Core integration, including vector types and distance functions. + +## Setup + +Install the [Pgvector.EntityFrameworkCore](https://www.nuget.org/packages/Pgvector.EntityFrameworkCore) package. Version 0.3.0 supports EF Core 9, 10 and 11. For EF Core 8, use version 0.2.2 and its [setup instructions](https://github.com/pgvector/pgvector-dotnet/blob/efcore-v0.2.2/README.md#entity-framework-core); the setup below is for version 0.3.0. + +Configure the plugin when configuring your context: + +```csharp +using Microsoft.EntityFrameworkCore; +using Pgvector.EntityFrameworkCore; + +optionsBuilder.UseNpgsql("", o => o.UseVector()); +``` + +If you use an [external NpgsqlDataSource](../index.md#using-an-external-npgsqldatasource), configure vector support on the data source as well: + +```csharp +using Npgsql; + +var dataSourceBuilder = new NpgsqlDataSourceBuilder(""); +dataSourceBuilder.UseVector(); +var dataSource = dataSourceBuilder.Build(); + +optionsBuilder.UseNpgsql(dataSource, o => o.UseVector()); +``` + +Install the pgvector extension on your PostgreSQL server. To have EF migrations enable it in your database, add the following to your context: + +```csharp +protected override void OnModelCreating(ModelBuilder modelBuilder) +{ + modelBuilder.HasPostgresExtension("vector"); +} +``` + +## Model and query + +Define a vector property with the number of dimensions used by your embedding model: + +```csharp +using System.ComponentModel.DataAnnotations.Schema; +using Pgvector; + +public class Item +{ + public int Id { get; set; } + public string Name { get; set; } = null!; + + [Column(TypeName = "vector(3)")] + public Vector? Embedding { get; set; } +} +``` + +The following query orders items by Euclidean (L2) distance to a query embedding and returns the five closest. The three-dimensional vector is only an example; use an embedding generated by your model in a real application. + +```csharp +using Pgvector.EntityFrameworkCore; + +var embedding = new Vector(new float[] { 1, 1, 1 }); +var items = await context.Set() + .OrderBy(i => i.Embedding!.L2Distance(embedding)) + .Take(5) + .Select(i => new { i.Id, i.Name }) + .ToListAsync(); +``` + +The distance is computed in PostgreSQL; the projection avoids retrieving the stored vectors. pgvector also supports other distance metrics and approximate nearest-neighbor indexes; see the [pgvector documentation](https://github.com/pgvector/pgvector) and [EF Core examples](https://github.com/pgvector/pgvector-dotnet#entity-framework-core). + +> [!WARNING] +> By default, EF loads vector properties when materializing entities, even if you only need the other properties. Embeddings can be large, so this can unnecessarily transfer and allocate substantial amounts of data. Disable automatic loading as shown [below](#avoiding-loading-vectors), or project only the properties you need. + +## Avoiding loading vectors + +Starting with EF Core 11, you can disable automatic loading of a vector property when entities are queried: + +```csharp +protected override void OnModelCreating(ModelBuilder modelBuilder) +{ + modelBuilder.HasPostgresExtension("vector"); + modelBuilder.Entity().Property(i => i.Embedding).Metadata.IsAutoLoaded = false; +} +``` + +The property can still be used in server-side queries, such as the distance calculation above. It is not populated on materialized entities, and an unloaded property is excluded from updates unless modified. To retrieve a vector, project it separately, for example `Select(i => new { i.Id, i.Embedding })`. Selecting it alongside an entity does not populate that entity's property, nor does returning its column from `FromSql` ([EF Core issue](https://github.com/dotnet/efcore/issues/39398)). + +In EF Core 8, 9 and 10, `IsAutoLoaded` is not available. Instead, use projections like the example above to retrieve only the properties you need; queries that materialize an entity still load its vector property. diff --git a/docs/toc.yml b/docs/toc.yml index 484d40cbe5..dd6770bf59 100644 --- a/docs/toc.yml +++ b/docs/toc.yml @@ -50,6 +50,8 @@ href: mapping/nts.md - name: Full text search href: mapping/full-text-search.md + - name: Vector search + href: mapping/vector-search.md - name: NodaTime href: mapping/nodatime.md - name: Arrays From 1de83154b0421ef49470b1398810140d45e8beae Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Thu, 26 Nov 2026 00:50:58 +0100 Subject: [PATCH 203/207] Document EF Core regex translation limitations (#485) Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- docs/mapping/translations.md | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/docs/mapping/translations.md b/docs/mapping/translations.md index 366677d900..f37f8d25aa 100644 --- a/docs/mapping/translations.md +++ b/docs/mapping/translations.md @@ -41,14 +41,22 @@ stringValue.TrimEnd(trimChar) | rtrim(stringValu stringValue.TrimStart() | ltrim(stringValue) stringValue.TrimStart(trimChar) | ltrim(stringValue, trimChar) EF.Functions.Reverse(value) | reverse(value) -Regex.IsMatch(stringValue, "^A+") | [stringValue ~ '^A+'](http://www.postgresql.org/docs/current/static/functions-matching.html#FUNCTIONS-POSIX-REGEXP) (with options) -Regex.IsMatch(stringValue, "^A+", regexOptions) | [stringValue ~ '^A+'](http://www.postgresql.org/docs/current/static/functions-matching.html#FUNCTIONS-POSIX-REGEXP) (with options) +Regex.IsMatch(stringValue, "^A+") | [stringValue ~ '^A+'](http://www.postgresql.org/docs/current/static/functions-matching.html#FUNCTIONS-POSIX-REGEXP) (with options) | [1](#regex-note) +Regex.IsMatch(stringValue, "^A+", regexOptions) | [stringValue ~ '^A+'](http://www.postgresql.org/docs/current/static/functions-matching.html#FUNCTIONS-POSIX-REGEXP) (with options) | [1](#regex-note) +Regex.Replace(stringValue, pattern, replacement) | [regexp_replace(stringValue, pattern, replacement, 'pg')](https://www.postgresql.org/docs/current/functions-matching.html#FUNCTIONS-POSIX-REGEXP) | [1](#regex-note) +Regex.Replace(stringValue, pattern, replacement, regexOptions) | [regexp_replace(stringValue, pattern, replacement, flags)](https://www.postgresql.org/docs/current/functions-matching.html#FUNCTIONS-POSIX-REGEXP) | [1](#regex-note) +Regex.Count(stringValue, pattern) | [regexp_count(stringValue, pattern, 1, 'p')](https://www.postgresql.org/docs/current/functions-matching.html#FUNCTIONS-POSIX-REGEXP) | [1](#regex-note) Requires PostgreSQL 15+ +Regex.Count(stringValue, pattern, regexOptions) | [regexp_count(stringValue, pattern, 1, flags)](https://www.postgresql.org/docs/current/functions-matching.html#FUNCTIONS-POSIX-REGEXP) | [1](#regex-note) Requires PostgreSQL 15+ string.Join(", ", a, b) | [concat_ws(', ', a, b)](https://www.postgresql.org/docs/current/functions-string.html#FUNCTIONS-STRING-OTHER) string.Join(", ", array) | [array_to_string(array, ', ', '')](https://www.postgresql.org/docs/current/functions-array.html#ARRAY-FUNCTIONS-TABLE) string.Join(", ", agg_strings) | [string_agg(agg_strings, ', ')](https://www.postgresql.org/docs/current/functions-aggregate.html#FUNCTIONS-AGGREGATE-TABLE) | See [Aggregate functions](#aggregate-functions). EF.Functions.StringToArray(s, "\|") | [string_agg(s, '\|')](https://www.postgresql.org/docs/current/functions-string.html#FUNCTION-STRING-TO-ARRAY) EF.Functions.StringToArray(s, "\|", "FOO") | [string_agg(s, '\|', 'FOO')](https://www.postgresql.org/docs/current/functions-string.html#FUNCTION-STRING-TO-ARRAY) +1 These translations use [PostgreSQL's regular expression syntax and semantics](https://www.postgresql.org/docs/current/functions-matching.html#FUNCTIONS-POSIX-REGEXP), not .NET's. In particular, unless `RegexOptions.Singleline` is specified, negated character classes such as `[^x]` do not match LF (`\n`), unlike in .NET: `a[^x]b` matches `"a\nb"` in .NET but not in PostgreSQL. Use client-side evaluation when exact .NET semantics are required. + +`RegexOptions` arguments must be constant, and `RightToLeft` and `ECMAScript` are not supported. Only `IgnoreCase`, `Multiline`, `Singleline` and `IgnorePatternWhitespace` affect the generated SQL. Only the listed static overloads are translated; instance methods, overloads accepting a match timeout or `MatchEvaluator`, and other `Regex` methods are not translated. + ## Date and time functions > [!NOTE] From 29d1edeccf3c70335ec1e128baa7160231697dc3 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Thu, 26 Nov 2026 11:43:10 +0100 Subject: [PATCH 204/207] Wire imported conceptual docs into documentation workflow Use site-root-relative links for cross-product pages and the API reference. Lint docs changes and notify npgsql/doc after main pushes. Keep agent guidance aligned with the new docs location. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .github/copilot-instructions.md | 2 ++ .github/workflows/docs.yml | 38 +++++++++++++++++++++++++++++++++ docs/.markdownlint.json | 16 ++++++++++++++ docs/index.md | 2 +- docs/release-notes/7.0.md | 2 +- docs/release-notes/8.0.md | 4 ++-- docs/release-notes/9.0.md | 2 +- docs/toc.yml | 2 +- 8 files changed, 62 insertions(+), 6 deletions(-) create mode 100644 .github/workflows/docs.yml create mode 100644 docs/.markdownlint.json diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index 9e3fc221b2..d687ae296d 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -2,6 +2,8 @@ This is the PostgreSQL provider for [Entity Framework Core](https://github.com/dotnet/efcore), built on top of [Npgsql](https://github.com/npgsql/npgsql). It translates EF Core LINQ queries into PostgreSQL SQL and handles PostgreSQL-specific features like arrays, JSON, ranges, full-text search, NodaTime, and PostGIS/NetTopologySuite. +Conceptual documentation lives in `docs/`. Update it as appropriate alongside code changes. + ## Build and Test Use the SDK pinned in `global.json` and dependency versions centralized in `Directory.Packages.props`. Consult EF APIs and test bases matching the pinned version; do not upgrade dependencies just to make a change compile. diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml new file mode 100644 index 0000000000..89bf10e4ae --- /dev/null +++ b/.github/workflows/docs.yml @@ -0,0 +1,38 @@ +name: Documentation + +on: + push: + branches: [main] + paths: ['docs/**'] + pull_request: + paths: ['docs/**'] + +permissions: + contents: read + +jobs: + lint: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v7 + + - name: Setup Node.js + uses: actions/setup-node@v7.0.0 + with: + node-version: 24.x + + - name: Run Markdownlint + run: | + npm i -g markdownlint-cli + markdownlint --config docs/.markdownlint.json "docs/**/*.md" + + dispatch: + needs: lint + if: github.event_name == 'push' && github.ref == 'refs/heads/main' && github.repository == 'npgsql/efcore.pg' + runs-on: ubuntu-latest + steps: + - name: Trigger documentation build + env: + GH_TOKEN: ${{ secrets.DOCS_DISPATCH_TOKEN }} + run: gh api --method POST repos/npgsql/doc/dispatches -f event_type=docs-changed diff --git a/docs/.markdownlint.json b/docs/.markdownlint.json new file mode 100644 index 0000000000..5d758ba0f3 --- /dev/null +++ b/docs/.markdownlint.json @@ -0,0 +1,16 @@ +{ + "default": true, + "MD011": false, + "MD013": false, + "MD024": false, + "MD028": false, + "MD033": { "allowed_elements": ["del", "a", "sup"] }, + "MD051": false, + "MD046": { + "style": "fenced" + }, + "MD055": false, + "MD056": false, + "MD059": false, + "MD060": false +} diff --git a/docs/index.md b/docs/index.md index 359b9a6c1b..7d1b6c633e 100644 --- a/docs/index.md +++ b/docs/index.md @@ -132,7 +132,7 @@ builder.Services.AddDbContextPool(opt => o => o.ConfigureDataSource(dataSourceBuilder => dataSourceBuilder.UseClientCertificate(certificate)))); ``` -`ConfigureDataSource()` provides access to a lower-level [`NpgsqlDataSourceBuilder`](../Npgsql/basic-usage.md#data-source) which you can use to configure all aspects of the Npgsql ADO.NET provider. +`ConfigureDataSource()` provides access to a lower-level [`NpgsqlDataSourceBuilder`](/doc/basic-usage.html#data-source) which you can use to configure all aspects of the Npgsql ADO.NET provider. > [!WARNING] > The EF provider internally creates an NpgsqlDataSource and uses that; for most configuration (e.g. connection string), the provider knows to switch between NpgsqlDataSources automatically. diff --git a/docs/release-notes/7.0.md b/docs/release-notes/7.0.md index 966ae01484..c5bdb46ba2 100644 --- a/docs/release-notes/7.0.md +++ b/docs/release-notes/7.0.md @@ -72,7 +72,7 @@ To the list of row value translations, see the [translations page](../mapping/tr ## Breaking changes -Note: version 7.0 of the lower-level Npgsql ADO.NET driver, which is used by the EF provider, also has some breaking changes. It's recommended to read the [release notes](../../Npgsql/release-notes/7.0.md) for that as well. +Note: version 7.0 of the lower-level Npgsql ADO.NET driver, which is used by the EF provider, also has some breaking changes. It's recommended to read the [release notes](/doc/release-notes/7.0.html) for that as well. ### Obsoleted UseXminAsConcurrencyToken diff --git a/docs/release-notes/8.0.md b/docs/release-notes/8.0.md index 280bf8dc3c..a27200bfc5 100644 --- a/docs/release-notes/8.0.md +++ b/docs/release-notes/8.0.md @@ -181,11 +181,11 @@ Version 8.0 contains many other smaller features and bug fixes, both on the EF s ## Breaking changes -Note: version 8.0 of the lower-level Npgsql ADO.NET driver, which is used by the EF provider, also has some breaking changes. It's recommended to read the [release notes](../../Npgsql/release-notes/8.0.md) for that as well. +Note: version 8.0 of the lower-level Npgsql ADO.NET driver, which is used by the EF provider, also has some breaking changes. It's recommended to read the [release notes](/doc/release-notes/8.0.html) for that as well. ### JSON POCO and other dynamic features now require an explicit opt-in -Because of the NativeAOT and trimming work done for Npgsql 8.0 ([release notes](../../Npgsql/release-notes/8.0.md)), certain features now require an explicit opt-in, which you must add either on your or on : +Because of the NativeAOT and trimming work done for Npgsql 8.0 ([release notes](/doc/release-notes/8.0.html)), certain features now require an explicit opt-in, which you must add either on your or on : PostgreSQL type | Default .NET type ---------------------------------------- | -------------------------- diff --git a/docs/release-notes/9.0.md b/docs/release-notes/9.0.md index 99908d405d..72d0f5478a 100644 --- a/docs/release-notes/9.0.md +++ b/docs/release-notes/9.0.md @@ -6,7 +6,7 @@ Npgsql.EntityFrameworkCore.PostgreSQL version 9.0 is out and available on [nuget The Npgsql EF provider is built on top of the lower-level Npgsql ADO.NET provider; the configuration interface between these two layers was less than ideal, and configuration been more difficult than it should have been. For version 9.0, the configuration experience has been considerably improved. -Since version 7, the Npgsql ADO.NET provider has been moving to [NpgsqlDataSource](../../Npgsql/basic-usage.md#data-source) as the preferred way of configuring connections and obtaining them. At the EF level, it has been possible to pass an NpgsqlDataSource instance to `UseNpgsql()`; but this required that the user separately configure a data source and manage it. In addition, features such as plugins and enums require support from both the EF and ADO.NET layers, forcing users to perform multiple setup actions at the different layers. +Since version 7, the Npgsql ADO.NET provider has been moving to [NpgsqlDataSource](/doc/basic-usage.html#data-source) as the preferred way of configuring connections and obtaining them. At the EF level, it has been possible to pass an NpgsqlDataSource instance to `UseNpgsql()`; but this required that the user separately configure a data source and manage it. In addition, features such as plugins and enums require support from both the EF and ADO.NET layers, forcing users to perform multiple setup actions at the different layers. With version 9, `UseNpgsql()` becomes a single point for configuration, for both the EF and ADO.NET levels. EF can now internally set up an NpgsqlDataSource, automatically applying all the necessary configuration to it, and also exposes an API to allow users to apply arbitrary configuration to it as well: diff --git a/docs/toc.yml b/docs/toc.yml index dd6770bf59..5e02b3be6f 100644 --- a/docs/toc.yml +++ b/docs/toc.yml @@ -71,4 +71,4 @@ - name: Other href: misc/other.md - name: API reference - href: "../../obj/api/EFCore.PG/" + href: /efcore/api/ From 42bcaf29d561c73fe59c769ac34e755fe8d8d4a1 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Thu, 26 Nov 2026 11:56:35 +0100 Subject: [PATCH 205/207] Use GitHub App token for docs dispatch Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .github/workflows/docs.yml | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index 89bf10e4ae..ab929e76bd 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -32,7 +32,16 @@ jobs: if: github.event_name == 'push' && github.ref == 'refs/heads/main' && github.repository == 'npgsql/efcore.pg' runs-on: ubuntu-latest steps: + - name: Create GitHub App token + id: app-token + uses: actions/create-github-app-token@v2 + with: + app-id: ${{ secrets.DOCS_APP_ID }} + private-key: ${{ secrets.DOCS_APP_PRIVATE_KEY }} + owner: npgsql + repositories: doc + - name: Trigger documentation build env: - GH_TOKEN: ${{ secrets.DOCS_DISPATCH_TOKEN }} + GH_TOKEN: ${{ steps.app-token.outputs.token }} run: gh api --method POST repos/npgsql/doc/dispatches -f event_type=docs-changed From 86d38958e128b6485215c7ca66690a1fd352417a Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Thu, 26 Nov 2026 13:10:54 +0100 Subject: [PATCH 206/207] Point API reference TOC entry at generated namespace page Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- docs/toc.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/toc.yml b/docs/toc.yml index 5e02b3be6f..cf55f1af77 100644 --- a/docs/toc.yml +++ b/docs/toc.yml @@ -71,4 +71,4 @@ - name: Other href: misc/other.md - name: API reference - href: /efcore/api/ + href: /efcore/api/Microsoft.EntityFrameworkCore.html From 8966c3fb152fc9b8f05f6298df10805b317d5a78 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Thu, 26 Nov 2026 13:12:33 +0100 Subject: [PATCH 207/207] Restore source API TOC reference and remove obsolete doc trigger workflow Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .github/workflows/trigger-doc-build.yml | 25 ------------------------- docs/toc.yml | 2 +- 2 files changed, 1 insertion(+), 26 deletions(-) delete mode 100644 .github/workflows/trigger-doc-build.yml diff --git a/.github/workflows/trigger-doc-build.yml b/.github/workflows/trigger-doc-build.yml deleted file mode 100644 index e8783c9e16..0000000000 --- a/.github/workflows/trigger-doc-build.yml +++ /dev/null @@ -1,25 +0,0 @@ -# This workflow triggers a rebuild of the Npgsql documentation site whenever changes are made to master, which represents our latest released version. -# This pulls in the newest source code for API doc generation. - -name: Trigger Documentation Build - -on: - push: - branches: - - docs - -permissions: - contents: read - -jobs: - build: - runs-on: ubuntu-latest - steps: - - name: Trigger documentation build - run: | - curl -X POST \ - -H "Authorization: token ${{ secrets.DOC_MGMT_TOKEN }}" \ - -H "Accept: application/vnd.github.everest-preview+json" \ - -H "Content-Type: application/json" \ - --data '{ "event_type": "Npgsql push to stable" }' \ - https://api.github.com/repos/npgsql/doc/dispatches diff --git a/docs/toc.yml b/docs/toc.yml index cf55f1af77..457bd5f829 100644 --- a/docs/toc.yml +++ b/docs/toc.yml @@ -71,4 +71,4 @@ - name: Other href: misc/other.md - name: API reference - href: /efcore/api/Microsoft.EntityFrameworkCore.html + href: ../../obj/api/EFCore.PG/