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()");Column Configuration
The AddColumn method returns a ColumnExpression with a fluent API:
AsPrimaryKey()-- marks the column as part of the primary keyAutoNumber()-- adds IDENTITY to the columnNotNull()/AllowNulls()-- controls nullabilityDefaultValue(value)-- sets a default value (int, long, double, or string)DefaultValueByExpression(expr)-- sets a default using a SQL expressionDefaultValueFromSequence(sequence)-- default from a named sequenceAddIndex(configure?)-- adds an index on this columnForeignKeyTo(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();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);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 RecreateGenerating DDL
cs
var migrator = new SqlServerMigrator();
var writer = new StringWriter();
table.WriteCreateStatement(migrator, writer);
Console.WriteLine(writer.ToString());