CodoMetis.ValueRanges.EFCore.PostgreSQL
11.0.0-preview.2
Prefix Reserved
See the version list below for details.
dotnet add package CodoMetis.ValueRanges.EFCore.PostgreSQL --version 11.0.0-preview.2
NuGet\Install-Package CodoMetis.ValueRanges.EFCore.PostgreSQL -Version 11.0.0-preview.2
<PackageReference Include="CodoMetis.ValueRanges.EFCore.PostgreSQL" Version="11.0.0-preview.2" />
<PackageVersion Include="CodoMetis.ValueRanges.EFCore.PostgreSQL" Version="11.0.0-preview.2" />
<PackageReference Include="CodoMetis.ValueRanges.EFCore.PostgreSQL" />
paket add CodoMetis.ValueRanges.EFCore.PostgreSQL --version 11.0.0-preview.2
#r "nuget: CodoMetis.ValueRanges.EFCore.PostgreSQL, 11.0.0-preview.2"
#:package CodoMetis.ValueRanges.EFCore.PostgreSQL@11.0.0-preview.2
#addin nuget:?package=CodoMetis.ValueRanges.EFCore.PostgreSQL&version=11.0.0-preview.2&prerelease
#tool nuget:?package=CodoMetis.ValueRanges.EFCore.PostgreSQL&version=11.0.0-preview.2&prerelease
CodoMetis.ValueRanges.EFCore.PostgreSQL
This package lets you store the types of
CodoMetis.ValueRanges in PostgreSQL with
Entity Framework Core and Npgsql. A range goes into a range column, a range set (DateRangeSet,
Int32RangeSet, …) into a multirange column, and a value set into a native array column. Your LINQ queries over them run in
the database as SQL, and they return the same results as the same code in memory.
dotnet add package CodoMetis.ValueRanges.EFCore.PostgreSQL
It needs PostgreSQL 16 or later. You turn it on with one line. You don't configure value converters, comparers or column types:
options.UseNpgsql(connectionString, npgsql => npgsql.UseValueRanges());
Which column each type gets
EF Core picks the column from the property type:
| Property type | Column type |
|---|---|
Int32Range |
int4range |
Int32RangeSet |
int4multirange |
DateRange |
daterange |
DateRangeSet |
datemultirange |
TimeRange |
timerange (custom type — see below) |
Float64Range |
float8range (custom type — see below) |
Float32Range |
float4range (custom type — see below) |
Float64Set |
double precision[] |
Float32Set |
real[] |
StringSet |
text[] |
GuidSet |
uuid[] |
| … and so on for every type |
Sets over your own element types work too. A property such as StringSet<AccessRight> is
recognized from the open generic, so there is no registration per element type to forget. Plain
string[] and List<Guid> properties keep Npgsql's own array mapping, and they can sit in the same
model.
Good to know:
TimeRangeneeds two opt-ins. PostgreSQL has no built-intimerange. You callHasPostgresRangeto create the type, andEnableUnmappedTypeson the data source. The EF Core guide shows both in TimeRange and the custom timerange type.- Migrations work with the custom range types. Before 11.0.0-preview.2 the second
migrations addfailed for a model with one of them. Use migrations with a custom range type shows the way round it for those versions. Float64RangeandFloat32Rangeneed the same two opt-ins. Create the types withHasPostgresRange("float8range", "double precision"), without asubtype_diff, which overflows a GiST index over very large values, andHasPostgresRange("float4range", "real"). Rows holdingNaNor an infinity throw when loaded. See Custom range types.- Sets are mapped as single values (scalars). The package brings its own mappings and translators for them. EF Core's primitive-collection support is never involved.
- Inside a
ToJson()column, a value is stored as its PostgreSQL text. This applies to a range, a multirange and a value set. A query into the document runs through a cast:CAST(doc ->> 'Period' AS daterange) @> @day. - That text is the database's form, not the JSON your API sends. A value set is stored as
"{a,b}", and theYearMonthtypes as month-aligned dates. A temporal value is stored at the server's microsecond, truncated the way Npgsql truncates a parameter, with the extremes as-infinityandinfinity. So the document, a column and a parameter all hold the same value. ExecuteUpdateof a value set inside a JSON document throws. You can set a range inside the document, and you can set the whole JSON property.- Scaffolding doesn't produce these types.
dotnet ef dbcontext scaffoldmaps range columns toNpgsqlRange<T>and array columns to plain arrays, because the package provides no design-time services. Change the property types yourself after scaffolding. Using these types is a decision about your model.
Query ranges
var day = new DateOnly(2024, 6, 15);
bookings.Where(b => b.Period.Contains(day)); // b."Period" @> @day
bookings.Where(b => b.Period.Overlaps(other)); // b."Period" && @other
bookings.Select(b => b.Period.Intersect(other)); // b."Period" * @other
bookings.OrderBy(b => b.Period.LowerBound()); // ORDER BY lower(b."Period"); no start sorts last
bookings.Select(b => b.Period.Merge(other)); // range_merge(b."Period", @other)
bookings.Select(b => b.BlockedDays.Gaps(month)); // datemultirange(@month) - b."BlockedDays"
bookings.Where(b => b.BlockedDays == someSet); // b."BlockedDays" = @set
bookings.GroupBy(b => b.CustomerId) // range_agg(b."Period")
.Select(g => g.Select(b => b.Period).RangeAgg());
Each comparison runs as one PostgreSQL operator:
| Method | Operator |
|---|---|
Contains |
@> |
Overlaps |
&& |
IsContainedBy |
<@ |
IsStrictlyLeftOf / IsStrictlyRightOf |
<< / >> |
DoesNotExtendLeftOf / DoesNotExtendRightOf |
&< / &> |
CompareTo against 0 |
<, <=, >, >=, = |
IsAdjacentTo runs as -|-. All of these work on ranges and on range sets, with either a range
or a multirange as the argument.
You can combine ranges in the database too:
Intersectruns as*.UnionandExceptturn both sides into multiranges and run as+and-. That matches the range set they return. So the union of two disjoint ranges comes back as a real two-element multirange, not an error.- The factories
CreateFinite,CreateUnboundedStartandCreateUnboundedEndrun as range constructor calls with a guard. The guard keeps the model's rule: bounds in the wrong order give an empty range.
The state checks map to PostgreSQL's range functions:
| Method | SQL |
|---|---|
IsEmpty() |
isempty |
IsUnboundedStart() |
lower_inf |
IsUnboundedEnd() |
upper_inf |
IsInfinity() |
lower_inf AND upper_inf |
IsFinite() |
NOT lower_inf AND NOT upper_inf AND NOT isempty |
Good to know:
- Discrete ranges come back exactly as in memory. PostgreSQL stores
int4range,int8rangeanddaterangehalf-open, as[lower, upper). The model keeps them closed, as[lower, upper]. The package makes up for the difference.UpperBound()runs asupper(x) - 1, andUpperBoundInclusive()asNOT upper_inf(x) AND NOT isempty(x). Results from the database always equal the results in memory, checked against a live PostgreSQL. LowerBound()andUpperBound()returnT?. PostgreSQL'slowerandupperreturnNULLwhen that side is unbounded or the range is empty. The in-memory methods returnnullin the same cases.- Aggregates over zero rows return
NULLin SQL. That is standard PostgreSQL behaviour. In memory,RangeAgg()over nothing returns the empty set.RangeIntersectAgg()returnsnullin both places. DateTimeRangebounds are stored as wall-clock time. They are written astimestampwithDateTimeKind.Unspecified. A UTC-kindedDateTimeis reinterpreted as wall-clock time, not converted.DateTimeOffsetRangebounds are stored in UTC. They are normalized to UTC fortimestamptz. You keep the instant, but the original offset doesn't come back.DateTime.MinValueandMaxValueare stored as-infinityandinfinity. That is Npgsql's default rule. Such a bound is still a finite bound that happens to be infinite. It stays different from an unbounded side, soupper_infstaysfalse.
Query value sets
users.Where(u => u.Roles.Contains("admin")); // u."Roles" @> ARRAY['admin']::text[]
users.Where(u => u.Roles.Overlaps(required)); // u."Roles" && @required
users.Where(u => u.Roles.IsSubsetOf(granted)); // u."Roles" <@ @granted
users.Where(u => u.Roles.Count > 2); // cardinality(u."Roles") > 2
users.Where(u => u.Roles.Remove("admin").IsEmpty); // cardinality(array_remove(…)) = 0
Contains always runs as @>, never as = ANY, so a plain GIN index on the column serves it.
Union, Add, Intersect and Except run as SQL too, on every set type, and give the
deduplicated, sorted set memory gives:
orders.Where(o => o.Codes.Union(more) == expected); // ARRAY((SELECT DISTINCT ON (vr0.x) vr0.x FROM unnest(…) …)) = @expected
orders.Where(o => o.Codes.Intersect(wanted).Count > 1);
ToRangeSet() on Int32Set, Int64Set and DateSet runs as SQL as well. You get the multirange
that holds the set's values, so a set column can go under the range operators:
// COALESCE((SELECT range_agg(daterange(vr0.x, vr0.x, '[]')) FROM unnest(b."BlackoutDays") AS vr0(x) WHERE vr0.x IS NOT NULL), '{}'::datemultirange) <@ b."Period"
bookings.Where(b => b.BlackoutDays.ToRangeSet().IsContainedBy(b.Period));
Good to know:
- On text the database sorts by the elements' UTF-8 bytes,
convert_to(x, 'UTF8'). That is Unicode code point order, the order aStringSethas in memory, on any database collation and encoding. So a textUnion,Add,IntersectorExceptcan be compared, counted, grouped, sorted and stored like any other. - Your own element types must sort as their underlying type does. An
Int32Set<OrderId>sorts the stored integers in the database and byOrderId.CompareToin memory. Vogen and StronglyTypedId compare by the underlying value.
What runs in memory only
These operations give the right answer in memory, and an EF Core query doesn't translate them.
Some would need composed SQL that isn't written; for others, SQL would answer differently. The
table says which.
In a Where, the query fails to translate. It fails loudly, instead of quietly fetching the whole
table. In the final Select, EF Core computes them in memory after it loads the rows.
| Operation | Why |
|---|---|
Length on the range types other than Int32Range and Int64Range |
not translated: a temporal range open to infinity fails in PostgreSQL |
Values() and Values(step) on a discrete range, Split on any range |
not translated: each would be generate_series collected into an array |
Shift, Expand on any range |
not translated: rebuilding the range from lower(x) + d answers differently for the empty range, time past midnight and a bound moved past the last date .NET holds |
LocalDateRange.Month, Quarter, Year and IsoWeek, and YearMonthRange.Quarter and Year, with an argument read from a column |
not translated: PostgreSQL has no dates before 4714-11-24 BC, so the month and the year that hold its first day have no start, with Npgsql's infinity conversions on or off. Built from values your code passes in, the range is sent as one constant, so comparing a column against a month runs as SQL. On DateRange they run as SQL |
ToInt32Set(), ToDateSet() and the other conversions from a range set to a set |
not translated: a multirange becomes an array only by listing every value in it, and it may be unbounded. The other direction, ToRangeSet(), runs as SQL |
Clamp(value) on a DateTimeRange, with a DateTime stored as timestamp with time zone |
not translated: GREATEST and LEAST would compare timestamp and timestamptz through the session's time zone. Map the property as timestamp without time zone and it runs as SQL |
the value set indexer, set[0] |
a row another tool wrote may not be canonical, arrays start at 1, and an index past the end is NULL where memory throws |
Everything else on the range, multirange and array surface runs in the database. The EF Core guide puts both halves side by side in What runs where.
Use NodaTime types
For NodaTime types, add
CodoMetis.ValueRanges.EFCore.PostgreSQL.NodaTime
and call npgsql.UseValueRangesNodaTime() instead.
Documentation
You can read every guide, with an API reference, on the documentation site.
- The EF Core guide shows every translation with the SQL it generates.
- Getting started walks you through a first entity, migration and query.
- The walkthrough follows one booking through a minimal API and PostgreSQL, and shows what changes at each step.
- The changelog lists what changed in each version.
License
MIT — see LICENSE.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net11.0 is compatible. |
-
net11.0
- CodoMetis.ValueRanges (>= 11.0.0-preview.2)
- Npgsql.EntityFrameworkCore.PostgreSQL (>= 11.0.0)
NuGet packages (2)
Showing the top 2 NuGet packages that depend on CodoMetis.ValueRanges.EFCore.PostgreSQL:
| Package | Downloads |
|---|---|
|
CodoMetis.ValueRanges.EFCore.PostgreSQL.NodaTime
NodaTime support for the CodoMetis.ValueRanges EF Core (Npgsql) plugin: maps LocalDateRange to daterange, LocalDateTimeRange to tsrange, InstantRange to tstzrange and YearMonthRange to a month-aligned daterange (plus their range set types, LocalDateRangeSet and so on, as multirange columns), bridging through NpgsqlRange<T> via Npgsql.EntityFrameworkCore.PostgreSQL.NodaTime. The full range algebra translates from LINQ to SQL exactly as for the BCL-based types — operators, bound accessors, range_merge, range_agg/range_intersect_agg, factories and multirange operations. v6 also maps the NodaTime value sets to native arrays — LocalDateSet to date[], LocalDateTimeSet to timestamp[], InstantSet to timestamptz[], LocalTimeSet to time[] (no CREATE TYPE needed, unlike timerange) and YearMonthSet to a month-aligned date[] — with the set algebra translating to the array operators (@>, &&, <@, cardinality). Enable with one line: options.UseNpgsql(..., npgsql => npgsql.UseValueRangesNodaTime()) — this implies both UseNodaTime() and UseValueRanges(). |
|
|
CodoMetis.ValueRanges.EFCore.PostgreSQL.SchemaKit
Typed Overlaps for CodoMetis.EFCore.SchemaKit.PostgreSQL's exclusion constraints over the range and range set columns of CodoMetis.ValueRanges: pg.Exclusion(pg.Equal(b => b.RoomId).Overlaps(b => b.Period)) compiles for a DateRange, a LocalDateRange, a DateRangeSet and every other range and range set type of CodoMetis.ValueRanges and CodoMetis.ValueRanges.NodaTime, and does not compile for any other property. Vocabulary only: SchemaKit renders the element (EXCLUDE USING gist ("RoomId" WITH =, "Period" WITH &&)) and creates the constraint. |
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 11.0.0-preview.3 | 0 | 11/30/2026 |
| 11.0.0-preview.2 | 7 | 11/30/2026 |
| 11.0.0-preview.1 | 228 | 11/28/2026 |
| 10.5.0 | 0 | 11/30/2026 |
| 10.4.0 | 1,023 | 10/26/2026 |
| 10.3.0 | 608 | 10/25/2026 |
| 10.2.0 | 893 | 10/25/2026 |
| 10.1.0 | 776 | 10/19/2026 |
| 10.0.0 | 343 | 10/19/2026 |
| 9.1.0 | 1,610 | 10/17/2026 |
| 9.0.0 | 399 | 10/11/2026 |
| 8.0.0 | 450 | 8/17/2026 |
| 7.0.0 | 235 | 8/17/2026 |
| 6.3.0 | 185 | 8/16/2026 |
| 6.2.1 | 189 | 8/16/2026 |
| 6.2.0 | 259 | 8/15/2026 |
| 6.1.0 | 168 | 8/14/2026 |
| 6.0.0 | 165 | 8/14/2026 |
| 5.0.0 | 159 | 8/13/2026 |
| 4.1.0 | 148 | 8/12/2026 |
The property type of a multirange column was renamed, and some queries and stored string sets answer differently: Migration from v10.x (https://github.com/CaffeinatedCoder/CodoMetis.ValueRanges/blob/main/docs/migration.md#migration-from-v10x).
Breaking
- EF Core: a multirange column is mapped from the range's own set type, DateRangeSet where it was RangeSet<DateRange, DateOnly>. Rename the property types. Migrations and the model snapshot need no change, since they name the provider type. Column types and SQL are unchanged, so no new migration follows (Migration (https://github.com/CaffeinatedCoder/CodoMetis.ValueRanges/blob/main/docs/migration.md#rename-rangesettrange-t-to-the-ranges-own-set-type)).
- EF Core: a final Select of ToRangeSet() runs in the database, where it ran in memory and returned the range set. A set holding int.MaxValue or long.MaxValue fails there with integer out of range, and a few results at a date type's ends don't load or count one range more. Call AsEnumerable() first for the in-memory answer (#487 (https://github.com/CaffeinatedCoder/CodoMetis.ValueRanges/issues/487), Migration (https://github.com/CaffeinatedCoder/CodoMetis.ValueRanges/blob/main/docs/migration.md#check-a-final-select-of-torangeset-at-the-ends-of-a-domain)).
- EF Core: a StringSet or StringSet<TElement> row that 10.x stored with an emoji beside a character from U+E000 to U+FFFF is in the old order, in a text[] column and inside a JSON column. Until you rewrite it, == against a set built in 11.0.0 is false in the database. One UPDATE for each rewrites those rows (#479 (https://github.com/CaffeinatedCoder/CodoMetis.ValueRanges/issues/479), Migration (https://github.com/CaffeinatedCoder/CodoMetis.ValueRanges/blob/main/docs/migration.md#rewrite-stored-string-sets-that-are-in-the-old-order)).
Added
- EF Core: ToRangeSet() on Int32Set, Int64Set and DateSet runs as SQL, so a set column can go under the range operators, as in b.Days.ToRangeSet().IsContainedBy(b.Stay) (Ask a range question of a set (https://github.com/CaffeinatedCoder/CodoMetis.ValueRanges/blob/main/docs/efcore.md#ask-a-range-question-of-a-set-with-torangeset)).
- EF Core: Union, Add, Intersect and Except on StringSet and StringSet<TElement> give the deduplicated, sorted set in SQL, sorted by convert_to(x, 'UTF8'). So GroupBy, Distinct, OrderBy, a Union of queries, Contains over several sets and an ExecuteUpdate value run over one, where they threw (Combine sets with Union (https://github.com/CaffeinatedCoder/CodoMetis.ValueRanges/blob/main/docs/efcore.md#combine-sets-with-union)).
- EF Core: the package is tested beside CodoMetis.EFCore.SchemaKit.PostgreSQL 11.0.0-preview.3, the EF Core 11 successor of EFCore.ComplexIndexes. Its exclusion constraints and GiST indexes work over a DateRange, a range set and a TimeRange column, declared with WithUncheckedOperator(x => x.Period, "&&") (Reject overlapping rows with an exclusion constraint (https://github.com/CaffeinatedCoder/CodoMetis.ValueRanges/blob/main/docs/efcore.md#reject-overlapping-rows-with-an-exclusion-constraint)).
Fixed
- EF Core: migrations add works a second time for a model with a TimeRange, Float64Range or Float32Range column, or a range set of one. It failed with a NullReferenceException, because nothing mapped the NpgsqlRange<T> property a snapshot records for a custom range type. MapRange is no longer needed (EF Core (https://github.com/CaffeinatedCoder/CodoMetis.ValueRanges/blob/main/docs/efcore.md#use-migrations-with-a-custom-range-type), #561 (https://github.com/CaffeinatedCoder/CodoMetis.ValueRanges/issues/561)).
- EF Core: DateRange.IsoWeek over a column translates under every culture. Under ar-SA translation threw ArgumentOutOfRangeException, and under th-TH the message the SQL raises named the year 10542. EF Core caches the SQL, so the first culture to translate a query decided its text (#552 (https://github.com/CaffeinatedCoder/CodoMetis.ValueRanges/issues/552)).
Full changelog: https://github.com/CaffeinatedCoder/CodoMetis.ValueRanges/blob/v11.0.0-preview.2/src/CodoMetis.ValueRanges.EFCore.PostgreSQL/CHANGELOG.md