Skip to content

Tables

The Table class in Weasel.SqlServer.Tables provides a fluent API for defining SQL Server tables, including columns, primary keys, foreign keys, indexes, and partitioning.

Defining a Table

cs
var table = new Table("dbo.users");

table.AddColumn<int>("id").AsPrimaryKey().AutoNumber();
table.AddColumn<string>("name").NotNull();
table.AddColumn<string>("email").NotNull().AddIndex(idx => idx.IsUnique = true);
table.AddColumn<DateTime>("created_at").DefaultValueByExpression("GETUTCDATE()");

snippet source | anchor

Column Configuration

The AddColumn method returns a ColumnExpression with a fluent API:

  • AsPrimaryKey() -- marks the column as part of the primary key
  • AutoNumber() -- adds IDENTITY to the column
  • NotNull() / AllowNulls() -- controls nullability
  • DefaultValue(value) -- sets a default value (int, long, double, or string)
  • DefaultValueByExpression(expr) -- sets a default using a SQL expression
  • DefaultValueFromSequence(sequence) -- default from a named sequence
  • AddIndex(configure?) -- adds an index on this column
  • ForeignKeyTo(table, column) -- adds a foreign key constraint

Foreign Keys

cs
var orders = new Table("dbo.orders");
orders.AddColumn<int>("id").AsPrimaryKey().AutoNumber();
orders.AddColumn<int>("user_id").NotNull()
    .ForeignKeyTo("dbo.users", "id", onDelete: Weasel.SqlServer.CascadeAction.Cascade);
orders.AddColumn<decimal>("total").NotNull();

snippet source | anchor

Indexes

cs
var index = new IndexDefinition("ix_users_email")
{
    Columns = new[] { "email" },
    IsUnique = true,
    IsClustered = false,
    Predicate = "email IS NOT NULL"  // filtered index
};
table.Indexes.Add(index);

snippet source | anchor

Indexes support IncludedColumns, FillFactor, SortOrder, and IsClustered properties.

Delta Detection

Compare the expected table definition against the actual database state:

cs
await using var conn = new SqlConnection(connectionString);
await conn.OpenAsync();

var delta = await table.FindDeltaAsync(conn);
// delta.Difference is None, Create, Update, or Recreate

snippet source | anchor

Generating DDL

cs
var migrator = new SqlServerMigrator();
var writer = new StringWriter();
table.WriteCreateStatement(migrator, writer);
Console.WriteLine(writer.ToString());

snippet source | anchor

Released under the MIT License.