NEW RasterizedDB 1.1.0 is out: sharding and the gateway, the message broker, roles and row-level security, compression, .NET on NuGet, and the enterprise edition. What's new ›
DOCS / C# / .NET CLIENT / EF CORE PROVIDER

EF Core provider

RasterizedDb.EntityFrameworkCore lets an Entity Framework Core application use RasterizedDB as its database, over the native protocol. Use it when your application already models its data with EF Core; for hand-written SQL use the ADO.NET driver directly (Commands and parameters).

Installing

The provider is the NuGet package RasterizedDb.EntityFrameworkCore, which brings RasterizedDb.Data with it:

sh
dotnet add package RasterizedDb.EntityFrameworkCore --version 1.1.0

See Getting started.

your target frameworkEF Core the provider uses
net10.0EF Core 10 (Microsoft.EntityFrameworkCore.Relational 10.0.5)
net8.0, net9.0EF Core 9 (Microsoft.EntityFrameworkCore.Relational 9.0.10)

For migrations and scaffolding you also need the EF Core tools, at the same EF Core version as the provider. On .NET 10:

sh
dotnet tool install --global dotnet-ef --version 10.0.5
dotnet add package Microsoft.EntityFrameworkCore.Design --version 10.0.5

On .NET 8 or 9, use EF Core 9 versions of both (for example 9.0.10).

Configuring the context

UseRasterizedDb takes a connection string, a RasterizedDbDataSource, or an open DbConnection:

csharp
using Microsoft.EntityFrameworkCore;

public class ShopContext(DbContextOptions<ShopContext> options) : DbContext(options)
{
    public DbSet<Customer> Customers => Set<Customer>();
    public DbSet<Order> Orders => Set<Order>();
}

public class Customer
{
    public int Id { get; set; }
    public string Name { get; set; } = "";
    public List<Order> Orders { get; set; } = [];
}

public class Order
{
    public long Id { get; set; }
    public int CustomerId { get; set; }
    public Customer Customer { get; set; } = null!;
    public decimal Total { get; set; }
    public DateTime PlacedAt { get; set; }
}

In an ASP.NET Core application:

csharp
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddDbContext<ShopContext>(options =>
    options.UseRasterizedDb(
        builder.Configuration.GetConnectionString("Shop"),
        rdb => rdb.EnableRetryOnFailure()));

var app = builder.Build();
app.Run();

Every connection string keyword from Connecting works here.

The overloads

calluse it when
UseRasterizedDb(string connectionString, Action<RasterizedDbDbContextOptionsBuilder>? options = null)the usual case
UseRasterizedDb(RasterizedDbDataSource dataSource, …)you already have a data source (one pool for the whole application, shared with ADO.NET code)
UseRasterizedDb(DbConnection connection, …, bool contextOwnsConnection = false)you manage the connection yourself

Each has a generic DbContextOptionsBuilder<TContext> form too.

csharp
using Microsoft.EntityFrameworkCore;
using RasterizedDb.Data;

var builder = WebApplication.CreateBuilder(args);

var dataSource = new RasterizedDbDataSource(builder.Configuration.GetConnectionString("Shop")!);
builder.Services.AddSingleton(dataSource);
builder.Services.AddDbContext<ShopContext>(options => options.UseRasterizedDb(dataSource));

var app = builder.Build();
app.Run();

Provider options

Inside the UseRasterizedDb(…, rdb => …) callback:

optiondefaultwhat it does
EnableRetryOnFailure(int maxRetryCount = 2, TimeSpan? maxRetryDelay = null)offRuns a unit of work again after a serialization failure (40001) or a deadlock (40P01). The longest delay is 5 seconds unless given. Nothing else is retried: a statement whose connection failed may have run.
MaxBatchSize(int)100The most statements SaveChanges sends in one round trip.
CommandTimeout(int)the connection string's Command TimeoutSeconds a command may wait for its answer.

The other options of EF Core's relational providers (MigrationsAssembly, MigrationsHistoryTable, and so on) are available as usual.

With EnableRetryOnFailure, a transaction you open yourself must run inside the execution strategy, as with any retrying EF Core provider:

csharp
var strategy = context.Database.CreateExecutionStrategy();
await strategy.ExecuteAsync(async () =>
{
    await using var transaction = await context.Database.BeginTransactionAsync();
    context.Orders.Add(new Order { CustomerId = 1, Total = 9.90m, PlacedAt = DateTime.UtcNow });
    await context.SaveChangesAsync();
    await transaction.CommitAsync();
});

How the provider talks to the server

  • Queries the provider generates run in the binary result format, the native path with typed values.
  • Raw SQL runs in the text format: FromSql, SqlQuery, ExecuteSql, and the statements of migrations. These may hold several statements and are read by column name.
  • SaveChanges sends its changes together, up to MaxBatchSize statements per round trip. A batch of more than one statement runs as one simple query, in the text format. Inserts, updates and deletes use RETURNING, so generated values come back from the statement that wrote them, and a concurrency conflict is seen as zero rows returned.
  • Transactions: context.Database.BeginTransactionAsync(), savepoints (CreateSavepointAsync, RollbackToSavepointAsync) and isolation levels work as in Transactions. Ambient TransactionScope transactions are not supported.

Type mapping

.NET property typecolumn type
boolboolean
shortsmallint
intinteger
longbigint
bytesmallint
floatreal
doubledouble precision
decimalnumeric; numeric(p,s) with HasPrecision(p, s)
stringtext; character varying(n) with HasMaxLength(n); character(n) with HasMaxLength(n) and IsFixedLength()
charcharacter(1)
byte[]bytea
Guiduuid
DateTimetimestamp with time zone
DateTimeOffsettimestamp with time zone
DateOnlydate
TimeOnlytime without time zone
TimeSpaninterval
an enumits underlying integer type (EF Core's default conversion)
T[] or List<T> of a type abovean array column: text[], integer[], …
an owned type mapped with ToJson()jsonb

Columns can be given other type names with HasColumnType: timestamp without time zone for a wall-clock DateTime, json, varchar(40), int4, float8 and the other PostgreSQL spellings. A type name the provider does not know (a domain, for example) is used as written, with the property's .NET mapping.

DateTime

A DateTime property maps to timestamp with time zone, an instant:

  • A UTC value is stored as it is; a Local one is converted to UTC; an Unspecified one is taken to be UTC already.
  • It always reads back with Kind Utc.

For a wall-clock time with no zone, use HasColumnType("timestamp without time zone"); it is written and read with Kind Unspecified.

Generated keys

An integer key that EF Core generates on add (the convention for an int or long named Id) becomes a serial, bigserial or smallserial column, and its value comes back with RETURNING on insert.

HiLo keys

UseHiLo takes keys from a sequence a block at a time, so a key is known as soon as the entity is added and one nextval serves a whole block of inserts:

csharp
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.HasSequence("order_ids").IncrementsBy(50);
    modelBuilder.Entity<Order>().Property(o => o.Id).UseHiLo("order_ids");
}
  • The sequence name defaults to ef_hilo_sequence, and the block size to 10 unless the sequence's IncrementsBy says otherwise.
  • The sequence is part of the model, so migrations and EnsureCreated create it.
  • HiLo makes int, long and short keys only.
  • Blocks are shared by every context of the application, so no key is handed out twice.

Array columns

A T[] or List<T> property of a mapped element type is an array column. In queries:

LINQSQL
tags.Contains(x)x = ANY (tags)
tags.Length, tags.Count, tags.Count()cardinality(tags)
tags.Any()cardinality(tags) > 0
tags[0], tags.First(), tags.ElementAt(i)tags[1], tags[i + 1] (SQL counts from 1)

A list held in a variable (ids.Contains(o.Id)) is a parameter list, not an array column, and becomes IN (…).

JSON columns

An owned type mapped with ToJson() is stored in one jsonb column, nested owned types and owned collections included:

csharp
// with `public DbSet<Account> Accounts => Set<Account>();` on the context
public class Account
{
    public int Id { get; set; }
    public string Name { get; set; } = "";
    public Preferences Preferences { get; set; } = new();
}

public class Preferences
{
    public string Theme { get; set; } = "light";
    public int PageSize { get; set; }
    public Address Billing { get; set; } = new();
}

public class Address
{
    public string City { get; set; } = "";
}

// in OnModelCreating:
modelBuilder.Entity<Account>().OwnsOne(a => a.Preferences, p =>
{
    p.ToJson();
    p.OwnsOne(x => x.Billing);
});

A member used in a query becomes a path into the document ("Preferences" ->> 'PageSize'), cast to the member's type when it is not text:

csharp
var bigPages = await context.Accounts.Where(a => a.Preferences.PageSize > 50).ToListAsync();

A change to part of a document is written in place with jsonb_set, not by rewriting the whole document.

Migrations

Migrations work with the standard EF Core tools:

sh
dotnet ef migrations add InitialCreate
dotnet ef database update

or from code at start-up:

csharp
await using var scope = app.Services.CreateAsyncScope();
var context = scope.ServiceProvider.GetRequiredService<ShopContext>();
await context.Database.MigrateAsync();

What to know:

  • Migrations emit PostgreSQL DDL, and run in the text format.

  • The applied migrations are recorded in __EFMigrationsHistory.

  • Locking. RasterizedDB has no advisory locks, so while migrating, a row in a table named __EFMigrationsLock is the lock. A second migrator waits up to two minutes for it and then fails. If a migration process died while holding it, the row stays; the error says so. When you are sure no migration is running, clear it:

    sql
    DELETE FROM "__EFMigrationsLock";
  • Idempotent scripts. dotnet ef migrations script --idempotent wraps each migration in a DO block that checks the history table first.

  • Schemas. Tables go in public unless the model names another schema, which is created with CREATE SCHEMA IF NOT EXISTS.

  • Computed columns (HasComputedColumnSql) are refused with NotSupportedException: RasterizedDB has no generated columns.

  • Statements that cannot run in a transaction. Each migration runs in a transaction, and DDL in it rolls back if the migration fails. A few statements are refused inside a transaction, such as CREATE DATABASE and the server's partition restructuring statements. Run them with migrationBuilder.Sql("…", suppressTransaction: true). See Transactions.

context.Database.EnsureCreatedAsync() and EnsureDeletedAsync() create and drop the database named in the connection string, through a separate connection to the server's default database. EnsureCreated creates the tables only when the database has none.

Migrations without EF Core

RasterizedDb.Data has a small migrator of its own, for applications that use ADO.NET only:

csharp
using RasterizedDb.Data;

await using var dataSource = new RasterizedDbDataSource("Host=127.0.0.1;Username=app;Password=change-me-now");

var migrator = new RasterizedDbMigrator()
    .Step("001_users", "CREATE TABLE users (id BIGSERIAL PRIMARY KEY, email TEXT NOT NULL)")
    .Step("002_unique_email", "ALTER TABLE users ADD CONSTRAINT users_email_key UNIQUE (email)")
    .Down("ALTER TABLE users DROP CONSTRAINT users_email_key");

var report = await migrator.ApplyAsync(dataSource);
Console.WriteLine($"applied: {string.Join(", ", report.Applied)}");
  • A step is a unique name and one or more statements, one statement per string. Each step runs in its own transaction together with the row that records it, so a step applies whole or not at all.
  • Every statement is checked before anything runs: a string with two statements, transaction control, or a placeholder is refused up front.
  • Applied steps are recorded, with a checksum, in rdb_migrations (change it with .HistoryTable("name")). Changing the text of an applied step is an error; add a new step instead.
  • VerifyAsync(dataSource) throws if anything is pending, for an application that must not start against an older schema. StatusAsync(connection) reports applied and pending steps without changing anything. RollbackAsync(connection, steps) undoes the newest steps with their Down statements.

Scaffolding an existing database

sh
dotnet ef dbcontext scaffold "Host=127.0.0.1;Username=app;Password=change-me-now;Database=shop" RasterizedDb.EntityFrameworkCore --output-dir Models

It reads tables, views, columns, primary and unique keys, foreign keys and indexes from the public schema, and writes a context that calls UseRasterizedDb.

LINQ translation

What the provider translates to SQL. Anything else is evaluated as EF Core normally does: in the final projection on the client, and elsewhere as an error.

areatranslated
queriesWhere, OrderBy/ThenBy, Skip/Take (LIMIT/OFFSET), joins, Include, GroupBy with Count, Sum, Min, Max, Average, Any/All (EXISTS), Contains over a list (IN), correlated subqueries (JOIN LATERAL)
bulkExecuteUpdate, ExecuteDelete
stringLength, ToUpper, ToLower (and the Invariant forms), Trim, TrimStart, TrimEnd (no arguments), PadLeft, PadRight, Replace, Substring, IndexOf(string), Contains, StartsWith, EndsWith, string.IsNullOrEmpty, string.IsNullOrWhiteSpace, string.Concat and +
pattern matchingEF.Functions.Like, EF.Functions.ILike (case-insensitive), Regex.IsMatch(text, pattern) as text ~ pattern, and with RegexOptions.IgnoreCase as ~*
Math, MathFAbs, Floor, Ceiling, Truncate, Sqrt, Pow, Max, Min, Round (with or without a digit count)
DateTime, DateTimeOffsetNow, UtcNow (now()), Today, Date, Year, Month, Day, Hour, Minute, Second, DayOfYear, DayOfWeek, AddYears, AddMonths, AddDays, AddHours, AddMinutes, AddSeconds, AddMilliseconds
DateOnly, TimeOnlyYear, Month, Day, DayOfYear, Hour, Minute, Second; AddYears, AddMonths, AddDays on DateOnly
TimeSpanTotalDays, TotalHours, TotalMinutes, TotalSeconds, TotalMilliseconds
otherGuid.NewGuid() (gen_random_uuid()), ToString() on numbers, bool and Guid
arrays, JSONsee Array columns and JSON columns

A Regex.IsMatch pattern is read by the server in PostgreSQL's regular expression syntax, which matches .NET's for the common constructs. Regex options other than IgnoreCase are not translated.

Limits

  • No LINQ composed over the elements of a JSON collection or of an array column (SelectMany over them, a Where inside them).
  • No spatial types.
  • No computed (generated) columns.
  • No ambient TransactionScope transactions.
  • Regex.IsMatch translates only with no options or RegexOptions.IgnoreCase.
  • The migrations lock is a row, not a server lock: a migration that dies holding it leaves it behind until you delete it.
✓ page rendered in 145 µs axum + tera + htmx · no other javascript