Skip to main content

StrongOf helps to implement primitives as a strong type that represents a domain object (e.g. UserId, EmailAddress, etc.). It is a simple class that wraps a value and provides a few helper methods to make it easier to work with. In contrast to other approaches, StrongOf is above all simple and performant - and not over-engineered.

Total Downloads
4.1K
4,119
Published
Oct 4, 2026
1mo ago

Get Started

dotnet add package StrongOf.EntityFrameworkCore --version 3.1.2
ProductVersions
.NET
net10.0net11.0net9.0

README

StrongOf.EntityFrameworkCore

Entity Framework Core value converters for StrongOf strongly-typed primitives. Seamlessly persist strong types like UserId, Email, or Amount to and from the database - without losing type safety.

NativeAOT boundary

This adapter currently depends on EF Core 8 and does not guarantee NativeAOT support for database operations. The core StrongOf factories are AOT-compatible, but that does not make EF Core model discovery, query compilation, providers or materialization compatible. Code analysis is enabled on this adapter without marking the assembly IsAotCompatible.

For EF Core's separate, version-dependent NativeAOT work, see NativeAOT and precompiled queries. The examples below are ordinary EF Core examples, not NativeAOT deployment examples.

Installation

dotnet add package StrongOf.EntityFrameworkCore

Quick Start

// Your domain types
public sealed class UserId(Guid value) : StrongGuid<UserId>(value), IStrongOf<Guid, UserId> { public static UserId Create(Guid value) => new(value); }
public sealed class Email(string value) : StrongString<Email>(value), IStrongOf<string, Email> { public static Email Create(string value) => new(value); }
public sealed class Amount(decimal value) : StrongDecimal<Amount>(value), IStrongOf<decimal, Amount> { public static Amount Create(decimal value) => new(value); }

// Your entity
public class Order
{
    public UserId Id { get; set; } = null!;
    public Email CustomerEmail { get; set; } = null!;
    public Amount Total { get; set; } = null!;
}

Usage

Option 1: Register Converters Once with ConfigureConventions (Recommended)

For most applications, the best approach is to register converters once in ConfigureConventions, so every property of that type is automatically converted across the model:

public class AppDbContext : DbContext
{
    public DbSet<Order> Orders => Set<Order>();

    protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder)
    {
        configurationBuilder.RegisterStrongOf<UserId, Guid>();
        configurationBuilder.RegisterStrongOf<Email, string>();
        configurationBuilder.RegisterStrongOf<Amount, decimal>();
    }
}

This is the recommended approach. You register each strong type once, and EF Core applies the converter everywhere that type appears.

ConfigureConventions uses EF Core's pre-convention activation path. StrongOfValueConverter<TStrong, TTarget> therefore exposes the public parameterless constructor EF Core expects for HaveConversion<TConversion>().

Option 2: Configure Properties in OnModelCreating

If you prefer explicit per-property control, or want the conversion next to property-specific facets such as length or precision, configure it in OnModelCreating:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Order>(entity =>
    {
        entity.Property(e => e.Id)
              .HasStrongOfConversion<UserId, Guid>();

        entity.Property(e => e.CustomerEmail)
              .HasStrongOfConversion<Email, string>()
              .HasMaxLength(256);

        entity.Property(e => e.Total)
              .HasStrongOfConversion<Amount, decimal>()
              .HasPrecision(18, 2);
    });
}

Option 3: Direct Converter Instance

You can also instantiate a converter directly, e.g. for use in custom model building logic:

StrongOfValueConverter<UserId, Guid> converter = new();

// Use with HasConversion directly
modelBuilder.Entity<Order>()
    .Property(e => e.Id)
    .HasConversion(converter);

Supported Types

Strong Type Base Database Type Converter
StrongGuid<T> uniqueidentifier / uuid StrongOfValueConverter<T, Guid>
StrongString<T> nvarchar / text StrongOfValueConverter<T, string>
StrongInt32<T> int StrongOfValueConverter<T, int>
StrongInt64<T> bigint StrongOfValueConverter<T, long>
StrongDecimal<T> decimal StrongOfValueConverter<T, decimal>
StrongChar<T> nchar(1) / char(1) StrongOfValueConverter<T, char>
StrongDateTime<T> datetime2 / timestamp StrongOfValueConverter<T, DateTime>
StrongDateTimeOffset<T> datetimeoffset / timestamptz StrongOfValueConverter<T, DateTimeOffset>

⚠️ EF Core LINQ Limitations

EF Core value converters work transparently for basic CRUD operations (insert, update, delete, read). However, there are important LINQ query limitations you should be aware of.

1. No Translation of Custom Methods or Properties

EF Core cannot translate methods or properties on your strong types into SQL. Only the underlying primitive value is known to the database.

// ❌ Will NOT work - EF Core cannot translate .Value into SQL
var users = await db.Users
    .Where(u => u.Id.Value == someGuid)
    .ToListAsync();

// βœ… Works - compare against another strong type instance
UserId targetId = new(someGuid);
var users = await db.Users
    .Where(u => u.Id == targetId)
    .ToListAsync();

2. Equality and Comparison

EF Core translates ==, !=, and comparison operators correctly when both sides are the same strong type (the converter unwraps both to the primitive for SQL generation):

UserId targetId = new(someGuid);

// βœ… Works - EF Core unwraps both sides
var user = await db.Users
    .FirstOrDefaultAsync(u => u.Id == targetId);

// βœ… Works - ordering is translated correctly
var sorted = await db.Users
    .OrderBy(u => u.Id)
    .ToListAsync();

3. No Contains with Mixed Types

When using Contains with a list of values, the list must be of the strong type, not the primitive:

Guid[] rawGuids = [guid1, guid2, guid3];
List<UserId> userIds = UserId.From(rawGuids)!;

// ❌ Does NOT work - cannot mix Guid[] with UserId property
var users = await db.Users
    .Where(u => rawGuids.Contains(u.Id))
    .ToListAsync();

// βœ… Works - same types on both sides
var users = await db.Users
    .Where(u => userIds.Contains(u.Id))
    .ToListAsync();

4. No SQL Translation for ToString() or Formatting

Calls to ToString(), IFormattable.ToString(format, provider), or any string formatting on strong types are not translatable to SQL:

// ❌ Will throw or evaluate client-side
var emails = await db.Users
    .Select(u => u.Email.ToString())
    .ToListAsync();

// βœ… Select the strong type, then format in memory
var users = await db.Users.ToListAsync();
var emails = users.Select(u => u.Email.Value).ToList();

5. Aggregations Work on Numeric Types

EF Core correctly unwraps numeric strong types for aggregate functions:

// βœ… Works - EF Core unwraps Amount to decimal for SUM
decimal? total = await db.Orders
    .SumAsync(o => (decimal?)o.Total);

Note: You may need to cast to the nullable primitive type (as shown above) because EF Core aggregate methods expect the underlying type, not the strong type.

6. General Rule of Thumb

Operation Works? Notes
Insert / Update / Delete βœ… Fully transparent
Where with == / != βœ… Both sides must be the same strong type
OrderBy / ThenBy βœ… Translated to SQL
Contains (same type) βœ… List and property must be the same strong type
Contains (mixed types) ❌ Use StrongType.From(...) to convert the list
.Value in LINQ ❌ Not translatable - use strong type comparisons
ToString() in LINQ ❌ Not translatable - format client-side
Aggregations (Sum, Avg) ⚠️ Cast to nullable primitive may be required
Custom methods in LINQ ❌ No SQL translation for user-defined methods

Best Practices

  1. Prefer ConfigureConventions when the same mapping should apply globally to every property of the strong type.
  2. Use OnModelCreating with HasStrongOfConversion when you want explicit mappings and property-specific facets in one place.
  3. Compare strong types against strong types in LINQ, not against raw primitives.
  4. Convert lists before querying - use StrongType.From(rawValues) to create a List<TStrong> for Contains queries.
  5. Format and transform client-side - select entities first, then access .Value or call .ToString() in memory.
  6. Test your queries - always verify that your LINQ queries translate to SQL correctly by checking the generated SQL (e.g., via logging or ToQueryString()).

Downloads by Version

Similar & Alternative Packages

Hand-picked matching NuGet libraries based on tags & ecosystem

Depended On By

Find packages that declare this package as a dependency. NuGet does not provide a reverse-dependency endpoint, so candidates are checked on demand.

Adoption Assessment

Assess this package against its supported frameworks, license, maintenance signals and dependency graph before making it a project standard.

Compatibility metadata lists 3 target frameworks; confirm the exact target used by your application.

Related Guides & Workflows

Learn how to evaluate, integrate, or audit this package in your .NET project.