Skip to content

Multi Tenancy

Christopher Davis edited this page Mar 14, 2016 · 2 revisions

Yet another built-in feature is the ability to add multi-tenant functionality. This feature allows you to design applications that may be used by multiple, independent application users that can use the application with total data independence. This contrasts with multi-instance software in that you can have one instance of your application and run many users with data separation. nHydrate implements a shared schema model with each tenant table having an assigned user that owns the data. The owner user is the logged-in database user. Queries against tenant tables only pull back data belonging to the database user that inserted the rows. This is based on the connection string defined when the EF context is created.

nHydrate implements this functionality by modifying the Entity Framework mapping files to route all queries to managed, internal views that pull back data only for the logged-in database user. In this way there is no way to pull back data not associated with the correct user using Entity Framework. This is an implementation of row level ownership. The permission functionality is completely transparent to the API. There is no need to append a user permission where clause to queries as this functionality is built into the framework.

To setup a multi tenant model, simply build a model as usual. On tables that are to be marked for tenant functionality just set the IsTenant property to true. That is the only setting you need to make. Upon generation, each tenant table has a hidden, managed column that stores the database user name. Each time a record is inserted into a tenant table, this column’s data is automatically set to the logged-in, database user.

To pull data out of a tenant table, simply write an Entity Framework, LINQ query as normal against the table. Remember there is no need to specify the user permission in the where clause as this is handled for you. All queries are routed through the hidden, managed view that is the filter for the table. In fact it is not possible to pull data directly from the table at all. There is no Entity Framework mapping directly to any tenant table. You can join and manipulate tenant tables normally with other tables (tenant and non-tenant) with complete transparency. All data permission is handled by the framework. The only caveat is that you need to create a database user for each tenant. You must specify that user in the connection string when you create an EF context. The only management you need to perform is database user management. As long as you connect to the database using the correct connection string, you will never get tenant data created by any other user.