Foreign keys

Define ordered child/parent columns and independent actions for update and delete.

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

Add a relationship

Parent key columns must identify a suitable primary/unique key. Child and parent arrays are positional: each child column corresponds to the parent column at the same index. Both tables and their compatible columns must already exist for this example. The Classic example uses IForeignKeyActions for independent update/delete actions; the older AddForeignKey overload supplies one action for both.

Orders belong to users

Classic

((IForeignKeyActions)Database).AddForeignKey(
    "FK_Orders_Users", "Orders", new[] { "UserId" },
    "Users", new[] { "Id" }, ForeignKeyConstraintType.Cascade,
    ForeignKeyConstraintType.NoAction);

Fluent

migration.Create.ForeignKey("FK_Orders_Users")
    .FromTable("Orders").WithColumns("UserId")
    .ToTable("Users").WithColumns("Id")
    .OnDelete(ForeignKeyConstraintType.Cascade)
    .OnUpdate(ForeignKeyConstraintType.NoAction);

Inside Up() / BuildUp(MigrationBuilder migration)

Remove a relationship

Remove dependent keys before incompatible table or key changes. Restore them only after the existing data satisfies the replacement relationship.

Remove the foreign key

Classic

Database.RemoveForeignKey("Orders", "FK_Orders_Users");

Fluent

migration.Delete.ForeignKey("FK_Orders_Users").FromTable("Orders");

Inside Up() / BuildUp(MigrationBuilder migration)

Database semantics

Supported actions depend on the database; do not assume every engine implements CASCADE, RESTRICT, SET NULL and SET DEFAULT identically. SQLite rebuilds preserve separate update/delete actions and validate integrity before an owned transaction commits. MATCH FULL and MATCH PARTIAL requests are rejected because SQLite does not enforce those semantics.

SetNull needs nullable child columns. Test action behavior using actual data, especially composite keys and partially NULL values. Oracle supports its own subset of foreign-key actions.