/DB

Sequences

Bind a column to a PostgreSQL sequence with [AutoIncrement].

updated 3 May 20261 min readv0.1.82

`[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

Generated DDL

CREATE SEQUENCE IF NOT EXISTS "log_entries_seq_seq" AS INTEGER START 1;

CREATE TABLE "log_entries" (
    "id"      UUID    NOT NULL,
    "seq"     INTEGER NOT NULL DEFAULT nextval('"log_entries_seq_seq"'),
    "message" TEXT    NOT NULL DEFAULT '',
    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 whatever value PostgreSQL assigned only if you explicitly re-fetch the row. The current insert builder does not return the generated value inline.


Notes

  • [AutoIncrement] does not imply [PrimaryKey]. Primary key and sequence are orthogonal — you can have a UUID primary key alongside a sequence counter column, as shown above.
  • Sequences are INTEGER by default. For a BIGINT sequence, override the column type: [Column(Type = "BIGINT"), AutoIncrement].