ASP.NET MVC Multi tenant Application using Single DB Multiple Schema : Calling Store Procedures from the application tries to access dbo tables

StackOverflow https://stackoverflow.com/questions/21597426

  •  07-10-2022
  •  | 
  •  

Question

I am developing a multi tenant application using ASP.NET MVC, SQL Server, Dapper with single db and multiple schema for each tenant. A tenant will be assigned a db user who owns the tenant schema. I have a set of tables in dbo and another set shared by all schema.

Say I have dbo.Tenant and anySchema.Table1. From my application with connection string set for anyschema user, if i call select * from Table1 it returns the values from anySchema.Table1. If i have the same query in a store procedure, it throws an error as it tries to access dbo.Table1.

I have provided execute access to dbo for the tenant db user as single SP is being shared by all tenant which is at dbo.SP_Name

How can i execute the store procedure logged in as the tenant db user, accessing Table1 of the anyschema so that single SP can be used by all tenants.

Était-ce utile?

La solution

Assume we have two users in our database tenant1 and tenant2 with their own schemas (also called tenant1 and tenant2).

We create a Contacts table for each tenant so we have tenant1.Contacts and tenant2.Contacts.

Within our application we execute the following SQL using Dapper. We are using a tenant specific connection string that uses the tenant's SQL Server login details.

select * from Contacts

Since we did not specify the schema within the SQL it is inferred from the default schema of the user under which the SQL executed. So for tenant1 it will query tenant1.Contacts and for tenant2 it will query tenant2.Contacts.

Now we'll create a stored procedure in the dbo schema that executes the same query:

CREATE PROCEDURE GetContacts
AS
BEGIN
    select * from Contacts
END
GO

Note that I've not specified a schema in the Stored Procedure's SQL.

When we execute the stored procedure from our application the schema of the stored procedure can still be inferred from the current user but the SQL within the SP infers the schema from that of the SP. So if the SP belongs to the dbo schema it will execute the query against the dbo.Contacts table.

This is what is happening in your situation. You have created a stored procedure in the dbo schema and expecting it to execute the SQL against the tenant's default schema.

You have a few options

  1. Pass the schema to your stored procedure as a parameter and use dynamic SQL - How to pass schema as parameter to a stored procedure in sql server?
  2. Create a version of the SP for each tenant e.g. tenant1.SP_Name, tenant2.SP_Name
  3. Don't use stored procedures.
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top