11.0 Release Notes
Npgsql.EntityFrameworkCore.PostgreSQL 11.0.0 is available on NuGet.
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 for examples and limitations.
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:
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.
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:
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<DateTime> ValidPeriod { get; set; }
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Employee>(b =>
{
b.Property(e => e.ValidPeriod)
.HasDefaultValueSql("tstzrange(now(), 'infinity', '[)')");
b.HasKey(e => new { e.EmployeeId, e.ValidPeriod })
.WithoutOverlaps();
});
}
This generates the following 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:
public class ProjectAssignment
{
public int AssignmentId { get; set; }
public int EmployeeId { get; set; }
public string ProjectName { get; set; }
public NpgsqlRange<DateTime> AssignmentPeriod { get; set; }
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<ProjectAssignment>(b =>
{
b.HasOne<Employee>()
.WithMany()
.HasForeignKey(e => new { e.EmployeeId, e.AssignmentPeriod })
.HasPrincipalKey(e => new { e.EmployeeId, e.ValidPeriod })
.WithPeriod();
});
}
This generates the following SQL:
ALTER TABLE project_assignments
ADD CONSTRAINT fk_emp_temporal
FOREIGN KEY (employee_id, PERIOD assignment_period)
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.
New translations
EFCore.PG 11 brings many new query translations across the board:
| .NET | SQL | Notes |
|---|---|---|
| EF.Functions.DateTrunc("month", value) | date_trunc('month', value) | Also supports NodaTime types and an optional time zone for timestamptz (#3831). |
| [EF.Functions.JsonPathExists(json, "\(.Age")](../mapping/translations.md#json-functions) | JSON_EXISTS(json, '\).Age') | PostgreSQL 17+ (#3733). | |
| EF.Functions.FuzzyStringMatchDaitchMokotoff(text) | daitch_mokotoff(text) | Requires fuzzystrmatch on PostgreSQL 16+ (#3524). |
| TimeZoneInfo.ConvertTimeBySystemTimeZoneId(dateTime, sourceTimeZoneId, destinationTimeZoneId) | (dateTime AT TIME ZONE sourceTimeZoneId) AT TIME ZONE destinationTimeZoneId | timestamp without time zone (#3938). |
| dateTime.Millisecond | floor(date_part('milliseconds', dateTime))::INT % 1000 | Also DateTimeOffset, TimeOnly (#3406). |
| dateTime.Microsecond | date_part('microseconds', dateTime)::INT % 1000 | Also DateTimeOffset, TimeOnly (#3406). |
| dateTime.AddMilliseconds(value) | dateTime + value * INTERVAL '1 milliseconds' | Also DateTimeOffset (#3449). |
| dateTime.AddMicroseconds(value) | dateTime + value * INTERVAL '1 microseconds' | Also DateTimeOffset (#3449). |
| LocalDateTime.ToDateTimeUnspecified() | No PG operation | NodaTime (#4048). |
| stringValue.IndexOf(value) | strpos(stringValue, value) - 1 | char overload (#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) | array1[:2] = array2 | Also Skip() and Skip().Take() (#3633). |
| array1.Intersect(array2).Any() | array1 && array2 | Now supports static readonly collections with non-null elements (#3638). |
| bytes.Any() | length(bytes) > 0 | byte[] mapped to bytea |
| bytes.Concat(bytes2) | bytes || bytes2 | byte[] columns mapped to bytea (#2200). |
| bitArray.Get(index) | get_bit(bitArray, index) = 1 | Also bitArray[index] (#2836). |
| EF.Functions.IntersectsBbox(geom1, geom2) | geom1 && geom2 | Thanks to @bjornharrtell! |
| EF.Functions.LineInterpolatePoint(lineString, fraction) | ST_LineInterpolatePoint(lineString, fraction) | #2632 |
| EF.Functions.LineMerge(geom) | ST_LineMerge(geom) | #2632 |
| EF.Functions.Scale(geom, xFactor, yFactor) | ST_Scale(geom, xFactor, yFactor) | Also supports a zFactor; scales relative to the coordinate origin (#829). |
| EF.Functions.SetSrid(geom, srid) | ST_SetSRID(geom, srid) | Sets SRID metadata without changing coordinates; use Transform for reprojection (#3245). |
The following hstore translations are now supported for Dictionary<string, string> and ImmutableDictionary<string, string>, with additional operations specific to immutable dictionaries (#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
- Generated
tsvectorcolumns and full-text expression indexes now support integer and exact-numeric inputs by casting them to text (#2615). MapEnumnow respects type-level[PgName]attributes when no PostgreSQL enum name is supplied (#3379).- Added
ModelBuilder.UseNoIdentityGeneration()to disable the model's default PostgreSQL identity generation strategy (#3723). - Covering indexes now support including properties nested within complex types mapped to regular columns.
- Indexes configured with
IsCreatedConcurrently()are now also dropped concurrently when removed by migrations (#3901). - Creating PostgreSQL extensions now uses
CASCADEto install their dependencies automatically (#3682). - Support specifying the encoding of newly created PostgreSQL databases with
ModelBuilder.UseDatabaseEncoding()(#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).
See the 11.0.0 milestone for the full list of issues.
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<MyContext>(...) 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).
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:
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
=> optionsBuilder.UseNpgsql("<connection string>", 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 and database concurrency failures for details (#3098).
Initial migration rollback removes model-level objects
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).
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).