Guides
Modelling data
How XOD reads your classes - primary keys, unique keys, indexes, validation, and the property types it stores.
Any public class with a parameterless constructor can be stored. XOD reads its public properties with a getter and a setter; each class is a table, each object a row.
Derived classes inherit XOD attributes ([PrimaryKey], [UniqueKey], [Property], [NotMapped] and
relationship attributes) from the virtual base properties they override. An attribute declared on the
override replaces the base property’s attribute of the same kind.
Primary keys
Every table has a primary key. You choose it in one of two ways.
By convention. If no property carries [PrimaryKey], a property named Id is the key. When it’s a
number, Guid or Guid?, XOD assigns it on insert.
public class Customer
{
public int Id { get; set; } // key, assigned 1, 2, 3...
public string Name { get; set; }
}
With [PrimaryKey]. Mark the property, of any primitive type, string, Guid or enum. You set the
value yourself.
public class Product
{
[PrimaryKey]
public string Sku { get; set; }
public string Name { get; set; }
}
Mark more than one property to make a composite key. To have XOD number a key you named yourself, add
[Property(AutoNumber = true)]:
public class Ticket
{
[PrimaryKey, Property(AutoNumber = true)]
public int Number { get; set; }
}
Inserting a second row with a key that’s already taken throws ReservedPrimaryKeyException.
A key part that isn’t an autonumber can’t be its type’s default: 0, false, an enum’s first member, an
empty Guid, or an empty or null string. Such a row is refused with MissingPrimaryKeyValueException, and
so is an update by such a key or an update, delete or InsertOrUpdate by an example that sets some key
parts and not others.
A number XOD handed out isn’t handed out again, even after its row is deleted and the database reopened;
dropping the table resets the numbering. IdentitySeed and IdentityIncrement set where numbering starts
and its step (see Attributes).
Unique keys
[UniqueKey] makes a property unique across the table and indexes it. A duplicate on insert or update
throws ReservedUniqueKeyException.
public class Account
{
public int Id { get; set; }
[UniqueKey, Required]
public string Email { get; set; }
}
Indexes
Primary and unique keys are indexed for you. Index any other property you filter on often:
public class Product
{
[PrimaryKey]
public string Sku { get; set; }
[Property(Indexed = true)]
public string Category { get; set; }
public decimal Price { get; set; }
}
var kitchen = db.Query<Product>(p => p.Category == "kitchen").ToList();
A query whose condition is on an indexed property reads the index instead of scanning the table, and returns
the same rows a scan would for every supported type. Indexed properties must be a primitive, number,
string, DateTime or Guid; a [Crypto] property can’t be indexed (see
Passwords and encryption). Indexes are kept in .xidx files beside each table and are
rebuilt if they’re missing.
Indexing is on by default; DatabaseOptions.EnableIndexing = false turns it off for the whole database.
Primary-key and unique checks compare text exactly and numbers by value whether indexing is on or off.
Validation
[Required] rejects a null or default value with RequiredPropertyException, on insert and on update.
Properties XOD doesn’t store
[NotMapped] keeps a property out of the files: useful for values you compute at runtime. Read-only
properties (no setter) aren’t stored either.
[NotMapped]
public string DisplayName => $"{Name} ({Sku})";
Supported types
| Kind | Types |
|---|---|
| Numbers and text | all primitives except nint and nuint, decimal, string, char |
| Dates and times | DateTime, DateTimeOffset, DateOnly, TimeOnly, TimeSpan |
| Other values | Guid, bool, enums, and nullable forms of any scalar above |
| Lists and arrays | T[], List<T>, interfaces List<T> implements (IList<T>, IEnumerable<T>, IReadOnlyList<T>), of scalars (including nullable scalars) or objects (see Relationships) |
| Maps | Dictionary<K, V>, SortedDictionary<K, V>, SortedList<K, V>, ImmutableDictionary<K, V>, ImmutableSortedDictionary<K, V>, IImmutableDictionary<K, V>, FrozenDictionary<K, V>, ConcurrentDictionary<K, V>, OrderedDictionary<K, V> (.NET 9), ReadOnlyDictionary<K, V>, IDictionary<K, V>, IReadOnlyDictionary<K, V>, Hashtable, non-generic SortedList, and constructable custom dictionary classes |
| Objects | another class as a property, stored as a row in its own table |
| Records | record classes, with settable properties |
Dates and times are written in a culture-independent round-trip format, so a database moves between
machines and locales unchanged. A string holding a lone UTF-16 surrogate (invalid text) is refused with
InvalidTextException.
Maps and string comparers
- Scalar keys and values: a map’s keys and values must be scalar types XOD stores as text. A
Dictionary<string, object>, a map of a class, interface orUri, or a map type XOD can’t construct is refused withXodExceptionwhen its class is first used. - String comparers are preserved: string-keyed
Dictionary,SortedDictionary,SortedList<,>,ImmutableDictionary,ImmutableSortedDictionary,FrozenDictionary,ConcurrentDictionaryand (.NET 9)OrderedDictionarystore and restoreStringComparer.Ordinal,OrdinalIgnoreCase,InvariantCulture,InvariantCultureIgnoreCaseand predefined culture comparers across writes, reopens and SQLSELECT. - Sorted string maps without a stored comparer read back in ordinal order on every machine.
- Custom comparers and unexposed comparers: user-defined comparer classes and map types without a public
comparer property (
Hashtable, non-genericSortedList,ReadOnlyDictionary) aren’t stored. Reading a map whose stored culture isn’t available on the reading machine throwsDatabaseFileException.
Refused types and object slots
A property XOD can’t store or read back is refused with XodException naming the property when its class is
first used (mark it [NotMapped] or change its type):
- unsupported value types:
Int128,Half,BigInteger,nint,nuint, tuples or custom structs (alone, nullable, or inside an array, list or map); - collections
List<T>can’t be assigned to, such asHashSet<T>,ArrayListor a custom subclass ofList<T>.
An object property refuses collections (lists, arrays, sets or maps) and scalars or structs it can’t read
back; declare the property as the concrete type, or pair it with [GenericTypeProperty] naming the full
type (System.Int32). A List<object> holds objects of a class only (refusing collections, scalars and
structs) and links already-stored keyed rows.
public enum EventKind { Private, Public }
public class Event
{
public int Id { get; set; }
public string Title { get; set; }
public DateOnly Day { get; set; }
public TimeOnly Starts { get; set; }
public TimeSpan Duration { get; set; }
public EventKind Kind { get; set; }
public Dictionary<string, string> Tags { get; set; }
public Venue Venue { get; set; }
}
public class Venue
{
public int Id { get; set; }
public string City { get; set; }
}
Values read back as written
A property reads back as you wrote it: an empty string reads back as ""; Guid.Empty, a default date and
a zero TimeSpan read back as stored; and null reads back as null even when a new instance of the class
initializes the property to something else.
public class Note
{
public int Id { get; set; }
public string Title { get; set; } = "Untitled";
public string Body { get; set; }
}
db.Insert(new Note { Title = null, Body = "" });
var note = db.Find<Note>(n => n.Id == 1);
// Title is null, Body is ""
Collections read back as written too: a map’s null value reads back as null, a list or array keeps its
null items, an empty map reads back empty, and an update that only reorders a list is saved.
Two edge cases still don’t round-trip null: a null stored as an XML attribute
(ValuePosition.Attribute) reads back as a new instance holds it (an attribute can’t express null), and a
null list or map whose property initializer creates an instance (List<string> Tags { get; set; } = new())
reads back initialized.
Large text and markup
[Markup] marks a property that holds HTML or XML. The XML format stores it in a CDATA section, so
the markup stays readable in the file instead of being escaped.
Where a value goes in the file
[Property(Position = ValuePosition.Attribute)] writes a short value as an XML attribute of the row
instead of a child element. It changes only the file’s layout, not how you use the property.