/DB

Sequences

Bind a column to a PostgreSQL sequence with [AutoIncrement] in Socigy.OpenSource.DB v0.3.2.

updated 5 Jun 20261 min readv0.3.2View as Markdown

`[AutoIncrement]`

Marks a property as a sequence-backed column. The migration tool creates a named PostgreSQL sequence and sets nextval('...') as the column default.

[Table("log_entries")]
public partial class LogEntry
{
    [PrimaryKey]
    public Guid Id { get; set; }

    [AutoIncrement]
    public int Seq { get; set; }

    public string Message { get; set; }
}

Sequence naming convention

The generated sequence name follows the pattern {table}_{column}_seq:

Table Column Sequence name
log_entries seq log_entries_seq_seq
orders order_number orders_order_number_seq

Pass a name to the attribute to override the convention: [AutoIncrement("custom_seq_name")].

Generated DDL

CREATE SEQUENCE IF NOT EXISTS "log_entries_seq_seq" AS INTEGER;

CREATE TABLE "log_entries" (
    "id"      UUID    NOT NULL,
    "seq"     INTEGER NOT NULL DEFAULT nextval('log_entries_seq_seq'),
    "message" TEXT    NOT NULL,
    PRIMARY KEY ("id")
);

Usage

Because [AutoIncrement] is effectively a database-side default, use ExcludeAutoFields() to let PostgreSQL assign the sequence value:

var entry = new LogEntry
{
    Id      = Guid.NewGuid(),
    Message = "Application started",
};

await entry.Insert()
    .WithConnection(conn)
    .ExcludeAutoFields()
    .ExecuteAsync();

After the insert, entry.Seq reflects the value PostgreSQL assigned only if you re-fetch the row or use WithValuePropagation(). The plain insert does not return the generated value inline.

Notes

  • [AutoIncrement] does not imply [PrimaryKey]. Primary key and sequence are orthogonal: you can keep a UUID primary key alongside a sequence counter column, as shown above.
  • Sequences are INTEGER by default. For a BIGINT sequence, declare the property as long (the sequence type follows the property type).
  • [AutoIncrement] is valid only on short, int, or long properties. Any other type is reported as error SCGDB001.