liveBook · Manning

Foreign key

As explained in Unit Testing Principles, Practices, and Patterns

A foreign key constraint requires values in one database column or set of columns to correspond to valid values in another table.

A foreign key constraint requires values in one column or column set to correspond to valid values in another table. During integration-test cleanup, it determines the order in which rows can be deleted without violating database integrity. section 10.3

Apply the constraint pragmatically in test-data cleanup:

  • Write the deletion script manually rather than generating table relationships or disabling integrity constraints. section 10.3
  • Run cleanup at the beginning of each test and remove regular data while preserving migration-controlled reference data. section 10.3
Listing 10.6. Base class for integration tests
public abstract class IntegrationTests
{
    private const string ConnectionString = "...";

    protected IntegrationTests()
    {
        ClearDatabase();
    }

    private void ClearDatabase()
    {
        string query =
            "DELETE FROM dbo.[User];" +    #1
            "DELETE FROM dbo.Company;";    #1

        using (var connection = new SqlConnection(ConnectionString))
        {
            var command = new SqlCommand(query, connection)
            {
                CommandType = CommandType.Text
            };

            connection.Open();
            command.ExecuteNonQuery();
        }
    }
}

Shows a base integration-test class that executes a fixed SQL deletion script before each test. section 10.3

How Unit Testing Principles, Practices, and Patterns covers it

How deep it goes
Explains deletion-order consequences but stops short of defining constraint syntax or relationship modeling.
Examples
Uses a manual SQL script in a C# integration-test base class to delete rows from User and Company tables.
What you can do after
Operate/configure integration-test isolation by writing deletion scripts that respect foreign key constraints.
How it connects
Connects foreign key constraints with integration testing, test-data cleanup, reference data, and database-schema migrations.

Also explained in

Compare how 18 books explain foreign key →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Unit Testing Principles, Practices, and Patterns. The section links point to the parts of the book it draws on.