Keys and constraints

Declare table invariants independently of column attributes.

Examples use Classic and Fluent tabs. Your choice follows you through the manual.

Add uniqueness and a check

Existing rows must satisfy a new constraint. A rebuild or ALTER operation can fail if duplicate or invalid data is present. CHECK expressions are trusted SQL and depend on the target engine. Primary keys, unique constraints, foreign keys and checks have typed definitions.

Add two named constraints

Classic

Database.AddUniqueConstraint("UQ_Users_Name", "Users", "Name");
Database.AddCheckConstraint("CK_Users_Id", "Users", "Id > 0");

Fluent

migration.Create.UniqueConstraint("UQ_Users_Name").OnTable("Users").WithColumns("Name");
migration.Create.CheckConstraint("CK_Users_Id").OnTable("Users").WithExpression("Id > 0");

Inside Up() / BuildUp(MigrationBuilder migration)

Remove the intended object

Use dedicated primary-key and foreign-key removal methods; generic RemoveConstraint is for unique/check constraints in the SQLite provider. Avoid RemoveAllConstraints unless the migration deliberately replaces every invariant.

Remove a check constraint

Classic

Database.RemoveConstraint("Users", "CK_Users_Id");

Fluent

migration.Delete.Constraint("CK_Users_Id").FromTable("Users");

Inside Up() / BuildUp(MigrationBuilder migration)

Constraint identity

GetTableConstraints returns ordered typed definitions. SQLite can return a null name for an unnamed legacy constraint; an autoindex name is not a substitute constraint name. PrimaryKeyExists checks the actual key name. MySQL reports the primary key name as PRIMARY.

Altering a column does not give that column ownership of a unique constraint. SQL Server implicit ownership markers are no longer used for deletion. Explicitly remove only the object your migration intends to change.