CRUD, upsert and bulk writes
On this page
Reduce work by choosing a write path
| Data shape | APIs to compare | Work avoided |
|---|---|---|
| Multiple new rows | InsertableRange, BulkInsertAsync | Let the provider process a batch and amortize construction and round trips |
| Same values for every matching row | Conditional Updatable<T>().SetColumns | Update directly without first loading and returning entities |
| Different values for each row | UpdatableRange, BulkUpdateAsync + UpdateColumns | Transfer and bind only changed columns |
| Insert or update on a unique key | Savable entity or collection overloads | Provider-native upsert avoids an application-side existence query |
See performance and benchmarks for native transport on SQL Server, PostgreSQL and MySQL, and transaction/prepared-statement reuse on SQLite. Bulk updates have fixed costs such as temporary tables; compare representative batch sizes before choosing.
Complete example: insert, partial update and business-key upsert
Install TORM and TORM.Sqlite using the quick start, put this program in Program.cs, and run dotnet run. A separate in-memory database keeps repeated runs independent.
using TORM;
await using var db = new OrmClient(new ConnectionConfig
{
DatabaseType = DatabaseType.Sqlite,
ConnectionString = "Data Source=:memory:"
});
await db.CodeFirst!.InitTableAsync<WriteDevice>();
var device = new WriteDevice { Code = "P-001", Name = "Inlet pump", Enabled = true };
device.Id = await db.Insertable(device).ExecuteReturnIdentityAsync();
var inserted = await db.InsertableRange(new[]
{
new WriteDevice { Code = "P-002", Name = "Outlet pump", Enabled = true },
new WriteDevice { Code = "P-003", Name = "Spare pump", Enabled = false }
}).BatchSize(500).ExecuteAsync();
Console.WriteLine($"Inserted batch: {inserted}");
await db.Updatable(new WriteDevice { Id = device.Id, Name = "Inlet pump A" })
.UpdateColumns(x => x.Name)
.ExecuteAsync();
var renamed = await db.Queryable<WriteDevice>().Where(x => x.Id == device.Id).FirstAsync()
?? throw new InvalidOperationException("The updated device was not found.");
Console.WriteLine($"Renamed: {renamed.Code}, {renamed.Name}, enabled: {renamed.Enabled}");
await db.Savable(new[]
{
new WriteDevice { Code = "P-002", Name = "Outlet pump A", Enabled = false },
new WriteDevice { Code = "P-004", Name = "Cooling pump", Enabled = true }
})
.WhereColumns(x => x.Code)
.UpdateColumns(x => new { x.Name, x.Enabled })
.ExecuteAsync();
foreach (var row in await db.Queryable<WriteDevice>().OrderBy(x => x.Code).ToListAsync())
{
Console.WriteLine($"{row.Code}: {row.Name}, enabled: {row.Enabled}");
}
var deleted = await db.Deletable<WriteDevice>().Where(x => x.Code == "P-003").ExecuteAsync();
Console.WriteLine($"Deleted: {deleted}, remaining: {await db.Queryable<WriteDevice>().CountAsync()}");
/// <summary>写入示例按数据库身份更新,并用设备编码作为唯一业务键。</summary>
[OrmTable("write_devices")]
[OrmIndex("ux_write_devices_code", nameof(Code), OrderByType.Asc, true)]
public sealed class WriteDevice
{
/// <summary>数据库自增主键,单条插入后显式接收返回值。</summary>
[OrmColumn(IsPrimaryKey = true, IsIdentity = true)]
public long Id { get; set; }
/// <summary>唯一业务编码,为 Upsert 提供冲突约束。</summary>
[OrmColumn(Length = 64, IsNullable = NullableState.Nullable)]
public string Code { get; set; } = "";
/// <summary>允许单独修改的设备名称。</summary>
[OrmColumn(Length = 128, IsNullable = NullableState.Nullable)]
public string Name { get; set; } = "";
/// <summary>部分更新名称时应保留数据库中的原值。</summary>
[OrmColumn(IsNullable = NullableState.Nullable)]
public bool Enabled { get; set; }
}Expected output:
Inserted batch: 2
Renamed: P-001, Inlet pump A, enabled: True
P-001: Inlet pump A, enabled: True
P-002: Outlet pump A, enabled: False
P-003: Spare pump, enabled: False
P-004: Cooling pump, enabled: True
Deleted: 1, remaining: 3UpdateColumns writes only selected columns and preserves other fields; entity updates match primary keys by default. UpdatableRange applies the same column-selection rules to multiple entities.
Insertable accepts one entity; collections use InsertableRange. ExecuteAsync returns affected rows. ExecuteReturnIdentityAsync returns a generated identity, assigned explicitly in this program. InsertColumns and IgnoreColumns select inserted columns; database defaults depend on the actual insert contract.
Savable and conflict keys
WhereColumns(x => x.Code) selects the conflict key; the database’s unique index enforces uniqueness under concurrent writes.
UpdateColumns limits the conflict-update branch; it does not restrict a new record’s insertion to those same columns. Supply complete business data for possible inserts and validate required codes before writing.
Conditional updates and deletion
When every matching row receives the same values, update directly in the database. Insert this fragment before the complete program’s type declaration:
var disabled = await db.Updatable<WriteDevice>()
.SetColumns(x => new WriteDevice { Enabled = false })
.Where(x => x.Code == "P-004")
.ExecuteAsync();
Console.WriteLine($"Disabled: {disabled}");It adds Disabled: 1 after the original output without first reading an entity. Update and delete predicates must include business and authorization scope. API access does not grant permission to modify every record.
Supported relational providers generate native upsert statements. UseLegacyMode() explicitly selects an older path. Conflict handling, triggers and affected-row counts remain database-specific; do not interpret them as portable inserted/updated business counts.
Optimistic concurrency: check the version in the UPDATE
Several callers can submit changes based on the same old state. Reading a version before an unconditional update still leaves a race between the commands. This independent program places the key, expected version and minimum stock in Where, then decrements stock and increments the version in the same update. Use the packages installed for this page:
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<Stock>();
await db.Insertable(new Stock { Id = 1, Quantity = 10, Version = 0 }).ExecuteAsync();
var expectedVersion = 0;
var requestedQuantity = 3;
for (var attempt = 1; attempt <= 2; attempt++)
{
var affected = await db.Updatable<Stock>()
.SetColumns(x => new Stock
{
Quantity = x.Quantity - requestedQuantity,
Version = x.Version + 1
})
.Where(x => x.Id == 1 && x.Version == expectedVersion && x.Quantity >= requestedQuantity)
.ExecuteAsync();
Console.WriteLine($"Attempt {attempt}: {affected}");
}
var saved = await db.Queryable<Stock>().Where(x => x.Id == 1).FirstAsync()
?? throw new InvalidOperationException("The stock row was not found.");
Console.WriteLine($"Quantity: {saved.Quantity}, version: {saved.Version}");
/// <summary>使用显式版本字段保护单条库存修改,版本约束由应用维护。</summary>
[OrmTable("versioned_stock")]
public sealed class Stock
{
/// <summary>唯一定位本次要修改的库存记录。</summary>
[OrmColumn(IsPrimaryKey = true)]
public long Id { get; set; }
/// <summary>扣减和下限检查在数据库同一条更新内执行。</summary>
[OrmColumn(IsNullable = NullableState.Nullable)]
public int Quantity { get; set; }
/// <summary>每次成功修改都递增,拒绝继续使用旧版本提交。</summary>
[OrmColumn(IsNullable = NullableState.Nullable)]
public int Version { get; set; }
}Expected output:
Attempt 1: 1
Attempt 2: 0
Quantity: 7, version: 1Both submissions carry version 0. The first succeeds and changes the stored version to 1; the second matches no row and does not decrement again. Sequential submissions verify rejection of a stale version; multiple clients rely on the database executing the same conditional update. The arithmetic on Quantity and Version runs in SQL, avoiding retrieval of the old stock for application-side calculation.
This version protocol belongs to the application. TORM does not enable optimistic concurrency from a property name. Every write path for the record must follow the same rule. Validate a positive requested quantity and add realm and data-authorization predicates to the actual scope.
An affected count of 0 means the combined predicate matched no row. A missing record, insufficient stock or a scope mismatch can produce the same result. Re-read within the allowed scope when a more specific response is needed; do not automatically replay a stock deduction. Changes spanning several records still need a transaction, and version checks do not replace request idempotency keys.
Bulk operations
var batch = new[]
{
new WriteDevice { Code = "P-005", Name = "Feed pump", Enabled = true },
new WriteDevice { Code = "P-006", Name = "Drain pump", Enabled = true }
};
await db.BulkCopy<WriteDevice>().Page(1000).BulkInsertAsync(batch);
Console.WriteLine($"After bulk insert: {await db.Queryable<WriteDevice>().CountAsync()}");Place the fragment before the complete program’s type declaration. It adds After bulk insert: 5 to the output.
BulkUpdateAsync updates batches; BulkMergeAsync combines inserts and updates. The base merge fallback classifies rows before bulk writing within a transaction. This differs from one native upsert statement, and concurrent writes still require unique constraints and an explicit isolation strategy.
Batching bounds command and parameter sizes. It does not automatically create a transaction for the entire business import. Use transactions and check provider-specific bulk behavior.
| Symptom | Check |
|---|---|
| Renaming clears a code or state | A partial object may be treated as a complete entity; specify UpdateColumns |
| Upsert always inserts or creates duplicates | Align WhereColumns with an actual unique constraint and a stable key |
| Some rows remain after a failed batch | Distinguish the business transaction from provider batch boundaries; BatchSize is not an atomicity switch |
| Affected counts change with providers | Check database-specific return semantics and verify final business state |