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:
namespace MultiTenancy.Migrations.NorthwindDB
{
[Migration(20170430194100)]
public class NorthwindDB_20170430_194100_MultiTenant
: AutoReversingMigration
{
public override void Up()
{
Alter.Table("Employees")
.AddColumn("TenantId").AsInt32()
.NotNullable().WithDefaultValue(1);
Alter.Table("Categories")
Alter.Table("Customers")
.AddColumn("TenantId").AsInt32()
.NotNullable().WithDefaultValue(1);
Alter.Table("Shippers")
.AddColumn("TenantId").AsInt32()
.NotNullable().WithDefaultValue(1);
Alter.Table("Suppliers")
.AddColumn("TenantId").AsInt32()
.NotNullable().WithDefaultValue(1);
Alter.Table("Orders")
Alter.Table("Products")
.AddColumn("TenantId").AsInt32()
.NotNullable().WithDefaultValue(1);
Alter.Table("Region")
.AddColumn("TenantId").AsInt32()
.NotNullable().WithDefaultValue(1);
Alter.Table("Territories")
.AddColumn("TenantId").AsInt32()
.NotNullable().WithDefaultValue(1);
}
}