Skip to content

SqlHelper.ExecuteUpsert method

Executes an UPSERT (insert or update) query on the connection and returns the number of affected rows. The key fields are used to determine whether an existing record is updated or a new record is inserted.

public static int ExecuteUpsert(this SqlInsert query, IDbConnection connection, 
    IEnumerable<string> keyFields, ExpectedRows expectedRows = ExpectedRows.Ignore, 
    IReadOnlyDictionary<string, object?>? parameters = null, ILogger? logger = null)
parameter description
query The insert query.
connection The connection.
keyFields List of key fields (e.g. primary key columns) used to match an existing record.
expectedRows The expected rows. Used to validate the expected number of affected rows.
parameters Values that override the query's parameters for this execution.
logger The logger.

Return Value

The number of affected rows.

Remarks

A native dialect-specific upsert is used when supported. Otherwise this method falls back to separate UPDATE and INSERT statements. That compatibility fallback is not atomic, so concurrent calls can race; there is no generic way to make this fallback atomic across dialects. Prefer a dialect with native upsert support when atomicity is required. The fallback reports one affected row for a successful logical upsert, and uses that value when checking expectedRows. Key matching is null-safe, so a null key value matches another null key value.

See Also