Mapping and CodeFirst
On this page
Attributes
| Attribute | Settings |
|---|---|
OrmTable | Name, description, connection ID and sharding settings |
OrmColumn | Column name, key, identity, length, database type, nullability, JSON and write exclusions |
OrmIgnore | Exclude a property |
OrmIndex | Single/composite indexes, order and uniqueness |
Complete example: create, read and reject duplicates
Install TORM and TORM.Sqlite using the quick start, replace Program.cs with the following, and run dotnet run. An in-memory database lasts for its connection. Opening that connection explicitly keeps the same database available across commands until the client is disposed.
using Microsoft.Data.Sqlite;
using TORM;
await using var db = new OrmClient(new ConnectionConfig
{
DatabaseType = DatabaseType.Sqlite,
ConnectionString = "Data Source=:memory:"
});
await db.Ado.GetOpenedConnectionAsync();
await db.CodeFirst!.InitTableAsync<DeviceCatalog>();
await db.Insertable(new DeviceCatalog { Code = "0007", Remark = null }).ExecuteAsync();
var saved = await db.Queryable<DeviceCatalog>().Where(x => x.Code == "0007").FirstAsync()
?? throw new InvalidOperationException("The inserted device was not found.");
Console.WriteLine($"Stored: {saved.Code}, remark is null: {saved.Remark is null}");
Console.WriteLine($"Display: {saved.DisplayName}");
try
{
await db.Insertable(new DeviceCatalog { Code = "0007" }).ExecuteAsync();
}
catch (SqliteException error) when (error.SqliteExtendedErrorCode == 2067)
{
Console.WriteLine("Duplicate code rejected.");
}
Console.WriteLine($"Rows: {await db.Queryable<DeviceCatalog>().CountAsync()}");
/// <summary>设备编码在数据库内保持唯一。</summary>
[OrmTable("device_catalog")]
[OrmIndex("ux_device_catalog_code", nameof(Code), OrderByType.Asc, true)]
public sealed class DeviceCatalog
{
/// <summary>数据库生成身份。</summary>
[OrmColumn(IsPrimaryKey = true, IsIdentity = true)]
public long Id { get; set; }
/// <summary>映射实际编码列。</summary>
[OrmColumn(ColumnName = "device_code", Length = 64, IsNullable = NullableState.Nullable)]
public string Code { get; set; } = "";
/// <summary>可选备注。</summary>
[OrmColumn(Length = 512, IsNullable = NullableState.Nullable)]
public string? Remark { get; set; }
/// <summary>读取后即时计算,不创建数据库列。</summary>
[OrmIgnore]
public string DisplayName => $"Device {Code}";
}Expected output:
Stored: 0007, remark is null: True
Display: Device 0007
Duplicate code rejected.
Rows: 1The SQL column is device_code; expressions and OrmIndex use CLR property names. SQLite error 2067 identifies a unique constraint violation; other providers use their own exception types.
Length describes the schema without providing consistent input-length validation across databases. SQLite does not reject longer text based on this setting.
Nullability and schema initialization
IsNullable has type NullableState; the default NotSpecified infers property nullability. This example explicitly permits nulls in non-key columns. CLR property initializers do not supply defaults for existing database nulls.
CodeFirst and DbMaintenance are nullable capability entry points with provider-specific support. Schema initialization does not perform application data migration.
Exclusions and binding
Ignore excludes a column; IsOnlyIgnoreInsert and IsOnlyIgnoreUpdate control individual write phases.
| Symptom | Check |
|---|---|
| SQL uses the wrong table or column | Check OrmTable.TableName and OrmColumn.ColumnName; expressions use CLR properties |
| A temporary read/write property appears in SQL | Apply OrmIgnore or the column’s Ignore to exclude it explicitly |
| Creating a unique index fails | Check existing duplicates; index creation cannot choose which business record to retain |
| A property initializer does not prevent null reads | Inspect stored data and nullability; initializers do not clean data or create default constraints |
ConnectionConfig.EnumAsString controls enum binding. UnspecifiedDateTimeKind determines how unmarked times are interpreted; agree on a time contract instead of relying on a server’s local timezone.
IsJson = true enables JSON column conversion. AOT applications still need JSON metadata for custom types. Provider registration and JSON contexts are separate responsibilities; see AOT.
OrmTable.ConfigId routes an entity to a configured database. Sharding is covered under advanced features.