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:
dotnet add package RasterizedDb.EntityFrameworkCore --version 1.1.0See Getting started.
| your target framework | EF Core the provider uses |
|---|---|
net10.0 | EF Core 10 (Microsoft.EntityFrameworkCore.Relational 10.0.5) |
net8.0, net9.0 | EF 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:
dotnet tool install --global dotnet-ef --version 10.0.5
dotnet add package Microsoft.EntityFrameworkCore.Design --version 10.0.5On .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:
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:
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
| call | use 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.
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:
| option | default | what it does |
|---|---|---|
EnableRetryOnFailure(int maxRetryCount = 2, TimeSpan? maxRetryDelay = null) | off | Runs 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) | 100 | The most statements SaveChanges sends in one round trip. |
CommandTimeout(int) | the connection string's Command Timeout | Seconds 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:
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. SaveChangessends its changes together, up toMaxBatchSizestatements per round trip. A batch of more than one statement runs as one simple query, in the text format. Inserts, updates and deletes useRETURNING, 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. AmbientTransactionScopetransactions are not supported.
Type mapping
| .NET property type | column type |
|---|---|
bool | boolean |
short | smallint |
int | integer |
long | bigint |
byte | smallint |
float | real |
double | double precision |
decimal | numeric; numeric(p,s) with HasPrecision(p, s) |
string | text; character varying(n) with HasMaxLength(n); character(n) with HasMaxLength(n) and IsFixedLength() |
char | character(1) |
byte[] | bytea |
Guid | uuid |
DateTime | timestamp with time zone |
DateTimeOffset | timestamp with time zone |
DateOnly | date |
TimeOnly | time without time zone |
TimeSpan | interval |
an enum | its underlying integer type (EF Core's default conversion) |
T[] or List<T> of a type above | an 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
Localone is converted to UTC; anUnspecifiedone is taken to be UTC already. - It always reads back with
KindUtc.
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:
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'sIncrementsBysays otherwise. - The sequence is part of the model, so migrations and
EnsureCreatedcreate it. - HiLo makes
int,longandshortkeys 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:
| LINQ | SQL |
|---|---|
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:
// 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:
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:
dotnet ef migrations add InitialCreate
dotnet ef database updateor from code at start-up:
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
__EFMigrationsLockis 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:sqlDELETE FROM "__EFMigrationsLock"; -
Idempotent scripts.
dotnet ef migrations script --idempotentwraps each migration in aDOblock that checks the history table first. -
Schemas. Tables go in
publicunless the model names another schema, which is created withCREATE SCHEMA IF NOT EXISTS. -
Computed columns (
HasComputedColumnSql) are refused withNotSupportedException: 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 DATABASEand the server's partition restructuring statements. Run them withmigrationBuilder.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:
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 theirDownstatements.
Scaffolding an existing database
dotnet ef dbcontext scaffold "Host=127.0.0.1;Username=app;Password=change-me-now;Database=shop" RasterizedDb.EntityFrameworkCore --output-dir ModelsIt 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.
| area | translated |
|---|---|
| queries | Where, 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) |
| bulk | ExecuteUpdate, ExecuteDelete |
string | Length, 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 matching | EF.Functions.Like, EF.Functions.ILike (case-insensitive), Regex.IsMatch(text, pattern) as text ~ pattern, and with RegexOptions.IgnoreCase as ~* |
Math, MathF | Abs, Floor, Ceiling, Truncate, Sqrt, Pow, Max, Min, Round (with or without a digit count) |
DateTime, DateTimeOffset | Now, UtcNow (now()), Today, Date, Year, Month, Day, Hour, Minute, Second, DayOfYear, DayOfWeek, AddYears, AddMonths, AddDays, AddHours, AddMinutes, AddSeconds, AddMilliseconds |
DateOnly, TimeOnly | Year, Month, Day, DayOfYear, Hour, Minute, Second; AddYears, AddMonths, AddDays on DateOnly |
TimeSpan | TotalDays, TotalHours, TotalMinutes, TotalSeconds, TotalMilliseconds |
| other | Guid.NewGuid() (gen_random_uuid()), ToString() on numbers, bool and Guid |
| arrays, JSON | see 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 (
SelectManyover them, aWhereinside them). - No spatial types.
- No computed (generated) columns.
- No ambient
TransactionScopetransactions. Regex.IsMatchtranslates only with no options orRegexOptions.IgnoreCase.- The migrations lock is a row, not a server lock: a migration that dies holding it leaves it behind until you delete it.