Guides
Reading data
Find one object, query many, page through a table in either direction, count, run SQL queries, and read asynchronously.
Find one
Find returns the first object that matches, or null:
var customer = db.Find<Customer>(c => c.Name == "Nadia");
if (customer is null) { /* not there */ }
First<T>() and Last<T>() return the first and last row of a table in stored order.
Query many
Query takes a lambda and returns every match as an IEnumerable<T>:
var open = db.Query<Order>(o => o.Status == "open").ToList();
When the condition is on the primary key, a unique key or an [Property(Indexed = true)] property,
XOD answers it from the index; otherwise it scans the table. Index what you filter on (see
Modelling data).
You can also query by example: pass an object, and XOD returns rows whose set properties match it.
var kitchen = db.Query(new Product { Category = "kitchen" });
An example matches the same way an index lookup does, with or without indexing: text compares exactly,
numbers compare by value (12.5m matches 12.50), and [Crypto(AES256)] properties match by their plain
value.
QueryDelegate and FindDelegate accept a compiled Func<T, bool> instead of an expression. They
always scan, so prefer the expression forms.
A predicate runs inside the read, so don’t write to the database from it: any write or maintenance call on
the same thread inside a read throws XodException (see
Writes from many threads).
Read a whole table
foreach (var order in db.Select<Order>())
{
// every row, read into a list before Select returns
}
Select<T>() and Query read every match before they return, so a large table is in memory at once; page
through it instead (below). SelectBackward<T>() reads from the last row to the first.
Page through a table
Select(skip, take) jumps straight to a position without reading the rows before it, so page 9,000 is
as fast as page 1:
var page = db.Select<Order>(skip: 20, take: 10).ToList(); // rows 21 to 30
var newest = db.Select<Order>(0, 10, backward: true).ToList(); // the last 10 rows
Count and test
int all = db.Count<Order>();
int open = db.Count<Order>(o => o.Status == "open");
bool any = db.Any<Order>(o => o.Id == 42);
Loading relationships
Every read method takes an include argument: "*" (the default) loads every relationship, or pass a
comma-separated list of property names to load only those. See
Relationships.
Every query builds referenced objects afresh from the current stored rows, so updates and deletes are
immediately visible and two queries never share mutable instances. An object reference to a deleted row
reads as null.
Querying with SQL
db.Sql runs a SQL SELECT, for the questions a lambda makes awkward: joins across tables, grouping and
totals. It only reads (INSERT, UPDATE and DELETE are refused).
SqlResult r = db.Sql(
"SELECT c.Name, COUNT(DISTINCT o.Id) AS orders, SUM(l.Quantity * l.UnitPrice) AS spent " +
"FROM Customer c JOIN \"Order\" o ON o.CustomerId = c.Id JOIN OrderLine l ON l.OrderId = o.Id " +
"WHERE o.Placed >= ? GROUP BY c.Name ORDER BY spent DESC LIMIT 10",
new DateOnly(2025, 1, 1));
foreach (object[] row in r.Rows)
Console.WriteLine($"{row[0]}: {row[1]} orders, {row[2]}");
A table is its class’s name (Customer), or its full name when two namespaces share it. A column is a
stored property. Order and Group are SQL words, so quote them: "Order".
Values go in as parameters, never into the text: ? takes the arguments in order, and @name takes
them from a dictionary.
var kitchen = db.Sql("SELECT Name, Price FROM Product WHERE Category = @cat AND Price < @max",
new Dictionary<string, object> { ["cat"] = "kitchen", ["max"] = 20m });
Into your own class: Sql<T> puts each column in the property of its name (any case), converting only
when nothing is lost:
public class Spend { public string Name { get; set; } public decimal Spent { get; set; } }
IReadOnlyList<Spend> top = db.Sql<Spend>(
"SELECT c.Name, SUM(l.Quantity * l.UnitPrice) AS Spent FROM OrderLine l " +
"JOIN \"Order\" o ON o.Id = l.OrderId JOIN Customer c ON c.Id = o.CustomerId GROUP BY c.Name");
Relationships read as paths and joins. A reference reads through dots, and a children collection joins like a table:
SELECT l."Order".Customer.Name, l.Product.Name, l.Quantity FROM OrderLine l WHERE l.Product.Category = 'kitchen'
SELECT c.Name, o.Status FROM Customer c JOIN c.Orders o
A dictionary reads by key (honouring its stored StringComparer, both on lookup and in Sql<T>
projections), and a list of values with ANY and CARDINALITY:
SELECT Name, Tags['vip'] FROM Customer WHERE 'newsletter' = ANY(Labels).
What it understands: inner, left and cross joins; WHERE, GROUP BY, HAVING, DISTINCT;
ORDER BY with NULLS FIRST or NULLS LAST; LIMIT and OFFSET; subqueries; CASE, CAST, LIKE and
ILIKE, IN, BETWEEN; COUNT, SUM, AVG, MIN, MAX; text, number and date functions
(LOWER, SUBSTRING, ROUND, EXTRACT, DATE_TRUNC and others); and VERIFY_HASH(column, plain) for a
hashed property (supports XOD 2.x and 1.x digests; returns false on NULL). Not supported: window
functions, WITH, UNION, and right or full joins.
How it compares and orders: as C# does. Text compares case-sensitively (ILIKE ignores case), and a
DateTime compares by its clock time, whatever its Kind. NULL follows SQL: x = NULL matches nothing,
so use IS NULL. Without ORDER BY, rows come in stored order. EXPLAIN SELECT ... shows which index each
table uses.
Indexes: a condition with =, a range or IN on a key, unique or indexed property is answered from
the index, as Query is, giving the same answer with or without it.
The result: r.Columns gives each column’s name and SQL type, and r.Rows holds the values as long
(INTEGER), double, decimal, string, bool, Guid, DateTime (TIMESTAMP), DateTimeOffset,
DateOnly, TimeOnly, TimeSpan (INTERVAL), a dictionary (MAP), a list (ARRAY), or null.
r.Warnings lists non-fatal caveats (such as an encrypted column read as NULL).
Errors throw XodSqlException, whose Code says what went wrong: XQ001 syntax error, XQ004 unknown
column, XQ005 type mismatch, and so on (see Exceptions).
Encrypted properties: a [Crypto(AES256)] column reads as plain text only when the database was opened
with its password or DatabaseOptions.PropertyEncryptionKey; otherwise it reads as NULL, with warning
XQ008. A hashed column reads as its hash.
To query a database from the command line without your classes, use xod query.
Async
The async methods return when the read is done, without blocking the calling thread, and take a
CancellationToken:
IReadOnlyList<Order> open = await db.QueryAsync<Order>(o => o.Status == "open");
Customer one = await db.FindAsync<Customer>(c => c.Id == 1);
IReadOnlyList<Customer> all = await db.SelectAsync<Customer>();
They return a read-only list, read in full before it is returned, as Query and Select do.
Concurrent reads
Reads run concurrently with each other from any number of threads sharing one XodContext. A read waits for
a write or another thread’s open transaction to finish, and a write waits for reads under way (see
Transactions).