Kalicz.StrongTypes.EfCore 2.0.0

There is a newer version of this package available.
See the version list below for details.
dotnet add package Kalicz.StrongTypes.EfCore --version 2.0.0
                    
NuGet\Install-Package Kalicz.StrongTypes.EfCore -Version 2.0.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Kalicz.StrongTypes.EfCore" Version="2.0.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Kalicz.StrongTypes.EfCore" Version="2.0.0" />
                    
Directory.Packages.props
<PackageReference Include="Kalicz.StrongTypes.EfCore" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Kalicz.StrongTypes.EfCore --version 2.0.0
                    
#r "nuget: Kalicz.StrongTypes.EfCore, 2.0.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Kalicz.StrongTypes.EfCore@2.0.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Kalicz.StrongTypes.EfCore&version=2.0.0
                    
Install as a Cake Addin
#tool nuget:?package=Kalicz.StrongTypes.EfCore&version=2.0.0
                    
Install as a Cake Tool

Kalicz.StrongTypes.EfCore

NuGet version Downloads License

EF Core plumbing for Kalicz.StrongTypes. Lets you use NonEmptyString, Email, MailAddress, Positive<T>, NonNegative<T>, Negative<T>, and NonPositive<T> as regular entity properties — they round-trip through scalar columns, and LINQ predicates over them translate to server-side SQL.

Install

dotnet add package Kalicz.StrongTypes.EfCore

The analyzer that ships with Kalicz.StrongTypes will nudge you to install this package whenever it sees a strong-type property on an EF-mapped entity.

Register

One call, on the options builder:

services.AddDbContext<AppDbContext>(options => options
    .UseSqlServer(connectionString)
    .UseStrongTypes());

UseStrongTypes() does three things:

  1. Registers a convention that attaches the right ValueConverter to every strong-type property on every mapped entity — you don't call HasConversion(...) by hand, and you don't override ConfigureConventions. The convention runs before EF's property-discovery pass, so wrappers never get misidentified as owned entity types.
  2. Registers a method-call translator so strongType.Unwrap() inside a LINQ predicate rewrites as a plain column reference, retyped with the underlying type's mapping so downstream string/number operators compose cleanly.
  3. Auto-maps every interval property to two endpoint columns (an EF Core complex type), so Start / End are queryable, indexable columns. A stored row that violates Start <= End throws InvalidOperationException when materialized — the interval's own constructor rejects it, no interceptor.

Works against every relational provider (SQL Server, PostgreSQL, SQLite, …).

Model

Just declare strong-type properties like any scalar:

public sealed class User
{
    public Guid Id { get; init; }
    public NonEmptyString Name { get; init; }
    public NonEmptyString? Nickname { get; init; }
    public Email? ContactEmail { get; init; }
    public MailAddress? BackupEmail { get; init; }
    public Positive<int> LoginCount { get; init; }
    public NonNegative<decimal> Balance { get; init; }
}

public sealed class AppDbContext(DbContextOptions<AppDbContext> options) : DbContext(options)
{
    public DbSet<User> Users => Set<User>();
}

Column shape on the database is the underlying type — nvarchar for NonEmptyString and for Email / MailAddress (the address string), int for Positive<int>, decimal(18,2) for NonNegative<decimal>, etc. Same for the nullable form (NonEmptyString?, Email?, Positive<int>?) — EF maps it to a nullable column.

An email column can be either Email (the wrapper — re-checks the 254-char cap on read) or the BCL MailAddress; the two convert to each other implicitly, so store whichever your domain already holds.

Non-public properties are wired too. An internal/private EF-mapped backing property — the usual DDD pattern behind a computed public view — gets its converter automatically once you map it, so you never hand-write HasConversion:

public sealed class Brand
{
    public Guid Id { get; init; }
    public NonEmptyString Name { get; init; }
    internal NonEmptyString? AliasesInternal { get; set; }   // EF-mapped storage
}

protected override void OnModelCreating(ModelBuilder modelBuilder) =>
    modelBuilder.Entity<Brand>()
        .Property(brand => brand.AliasesInternal)
        .HasColumnName("Aliases");                            // converter is automatic

Intervals

The interval types (FiniteInterval<T>, Interval<T>, IntervalFrom<T>, IntervalUntil<T>) auto-map too, in one of two shapes:

  • Two endpoint columns — the UseStrongTypes() default. Start / End are queryable, indexable columns, but the shape is inclusive-only: no inclusivity is stored.
  • One JSON column — opt in with HasIntervalJsonConversion. Carries each value's inclusivity in the payload.

Both re-validate Start <= End on read: a stored row that violates it throws when materialized — the JSON shape through its converter, the two-column shape through the interval's own constructor.

Two endpoint columns (default)

UseStrongTypes() maps each interval property to two scalar endpoint columns as an EF Core complex type — each endpoint its own queryable, indexable column, nullable exactly when the variant's endpoint is. Endpoint access in LINQ translates to plain column references:

var hits = await db.Bookings.Where(b => b.Window.Start <= at && at <= b.Window.End).ToListAsync();

Endpoint columns are named Start / End, prefixed with the property name (Window_Start) when two intervals on the same entity would clash. A nullable interval property additionally gets a shadow discriminator column, keeping a null property distinct from a stored interval whose endpoints are all NULL (a fully-unbounded Interval<T>).

To rename the columns, pass startName / endName — this overload also returns the complex-property builder for further tweaks, and is how you get two-column mapping without UseStrongTypes():

modelBuilder.Entity<Booking>()
    .HasIntervalColumns(b => b.Window, startName: "WindowStart", endName: "WindowEnd");

To index an endpoint, add the index in a migration — EF Core cannot declare an index over a complex-type member (HasIndex(b => b.Window.Start) is rejected), but the endpoint is a plain column on the entity's table:

migrationBuilder.CreateIndex(name: "IX_Bookings_WindowStart", table: "Bookings", column: "WindowStart");

Storing inclusivity

The two endpoint columns hold Start and End only — so every interval reads back with both bounds inclusive, and a half-open [start, end) value saved through them comes back [start, end]. To keep inclusivity, pick one:

  • One JSON column (below) — each value carries its own bounds.
  • Model the columns yourself — persist the endpoints and a flag as your own scalar columns, and expose the interval as an unmapped computed property:
public class Shift
{
    public int Id { get; init; }
    public int StartHour { get; set; }
    public int EndHour { get; set; }
    public bool EndInclusive { get; set; }

    [NotMapped]                                   // EF maps the four scalars; this is your view over them
    public FiniteInterval<int> Window
    {
        get => FiniteInterval.Create(StartHour, EndHour, endInclusive: EndInclusive);
        set => (StartHour, EndHour, EndInclusive) = (value.Start, value.End, value.EndInclusive);
    }
}

One JSON column

Opt in with HasIntervalJsonConversion, on the entity builder or on the property builder (the latter also handles nullable properties). The interval round-trips through its validating JSON converter into a single column (jsonb on PostgreSQL, nvarchar(max) on SQL Server), and endpoint access in LINQ translates to a server-side JSON path lookup (JSON_VALUE(...) on SQL Server, ->> on PostgreSQL) — still filterable and orderable, just not index-backed:

modelBuilder.Entity<Booking>()
    .HasIntervalJsonConversion(b => b.Window);

modelBuilder.Entity<Booking>()
    .Property(b => b.MaybeWindow)              // FiniteInterval<int>?
    .HasIntervalJsonConversion();

Each value carries its own inclusivity in the payload — a bound flag written only when it isn't the inclusive default, read back as inclusive when absent. To pin a fixed convention (no flags in the JSON at all), map the column with a custom value converter over a subclassed IntervalJsonConverter<TInterval>.

Filtering

Equality, null checks, ordering, and grouping work directly on the strong type:

// Equality against a strong-type value
var needle = NonEmptyString.Create("alice");
var user = await db.Users.SingleOrDefaultAsync(u => u.Name == needle);

// Null / not-null on the nullable form
var withNickname = await db.Users
    .Where(u => u.Nickname != null)
    .ToListAsync();

// OrderBy directly on the wrapper
var ordered = await db.Users
    .OrderBy(u => u.Name)
    .ToListAsync();

For anything that needs the underlying value — string operators like Contains / StartsWith, arithmetic on numerics, EF.Functions.Like — call Unwrap():

// StartsWith / Contains / EndsWith translate server-side via Unwrap()
var search = await db.Users
    .Where(u => u.Name.Unwrap().StartsWith("ali"))
    .ToListAsync();

// EF.Functions.Like — the canonical case
var wildcard = await db.Users
    .Where(u => EF.Functions.Like(u.Name.Unwrap(), "ali%"))
    .ToListAsync();

// Arithmetic on numeric wrappers. Cast to long if you want to guard
// against int32 overflow on wide columns.
var active = await db.Users
    .Where(u => u.LoginCount.Unwrap() * 2 > 10)
    .ToListAsync();

// Works the same for EF.Functions.Collate, string.IsNullOrEmpty, etc.
var caseInsensitive = await db.Users
    .Where(u => EF.Functions.Collate(u.Name.Unwrap(), "SQL_Latin1_General_CP1_CI_AS") == "alice")
    .ToListAsync();

Unwrap() is a marker call for EF — the in-memory implementation just returns .Value, so the same expression works fine if you ever need to run a LINQ query client-side. The translator rewrites the call to a column reference before SQL generation.

License

MIT. See the StrongTypes repository.

Product Compatible and additional computed target framework versions.
.NET net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
2.0.1 715 7/17/2026
2.0.0 136 7/16/2026
1.2.0 164 7/12/2026
1.1.1 169 6/24/2026
1.1.0 720 5/5/2026
1.0.1 136 4/23/2026