简体   繁体   中英

Entity Framework Multi-Tenant Architecture With Multiple Databases & Generics

I'm needing to build a multi-tenanted application. The code is completely shared for each company but each company has its own database.

Each company accesses the application through a Web API passing their own 'API Key'. This key is used to 'look up' the company specific configuration details within the master database's 'GlobalCompanies' table that holds company specific details including the database details and full connection strings.

My goal, to set up a new customer, is to simply run some scripts to create a new database and update this 'GlobalCompanies' table with the new database details and everything will just work!

So, no configuration information within the web.config file except perhaps the master database holding the configuration details.

The flow would therefore be:

  1. Browser calls a Web API method and passes API Key
  2. Application uses API Key and determines which database is being used
  3. Application uses common code but applies database operations to the company-specific database.

I found this article Repository Pattern with Entity Framework 4.1 and Code First which gives me an insight to generics for the Repository pattern but I'm unsure how I would dynamically create and utilise different DBContexts? (if even that is the correct approach)?

I have done this before with ADO.net using different connection strings but ideally I'd like to utilize Entity Framework and generics.

Could someone please point me in the right direction? I couldn't find any specific examples of this architecture.

EF is the same as what you did with ADO.Net. You just pass a different connection string to the constructor of the context. (The default constructor with no parameter will take the connection string from the config file.) The context won't care where the connection string comes from - config file, master database, constructed by the calling code - it will just use it.

Of course, if the connection string is malformed, or points to a db which doesn't contain the expected tables, then there will be problems. But I'm sure that you'd expect that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM