Adding Tenants Table and TenantId Field

    So, we first need a Tenants table.

    As Northwind tables already have records, we’ll define a primary tenant with ID 1, and set all existing records TenantId to it.

    DefaultDB_20170430_134800_MultiTenant.cs:

    I have created Tenants table in Default database where user tables are. Here we add 3 predefined tenants. We actually only need first one with ID 1.

    Let’s write another migration for Nortwhind database to add TenantId column to required tables:

    NorthwindDB_20160110_093500_MultiTenant.cs:

    1. namespace MultiTenancy.Migrations.NorthwindDB
    2. {
    3. [Migration(20170430194100)]
    4. public class NorthwindDB_20170430_194100_MultiTenant
    5. : AutoReversingMigration
    6. {
    7. public override void Up()
    8. {
    9. Alter.Table("Employees")
    10. .AddColumn("TenantId").AsInt32()
    11. .NotNullable().WithDefaultValue(1);
    12. Alter.Table("Categories")
    13. Alter.Table("Customers")
    14. .AddColumn("TenantId").AsInt32()
    15. .NotNullable().WithDefaultValue(1);
    16. Alter.Table("Shippers")
    17. .AddColumn("TenantId").AsInt32()
    18. .NotNullable().WithDefaultValue(1);
    19. Alter.Table("Suppliers")
    20. .AddColumn("TenantId").AsInt32()
    21. .NotNullable().WithDefaultValue(1);
    22. Alter.Table("Orders")
    23. Alter.Table("Products")
    24. .AddColumn("TenantId").AsInt32()
    25. .NotNullable().WithDefaultValue(1);
    26. Alter.Table("Region")
    27. .AddColumn("TenantId").AsInt32()
    28. .NotNullable().WithDefaultValue(1);
    29. Alter.Table("Territories")
    30. .AddColumn("TenantId").AsInt32()
    31. .NotNullable().WithDefaultValue(1);
    32. }
    33. }