1

I'm looking for the best way to set the database based on a sub-domain using entity framework.

  1. Connect to Master DB using default EF process
  2. Read sub-domain of current request
  3. Access Master DB to read the connection string of the sub-domain
  4. Set EF context to use the DB of the sub-domain
  5. All EF connections should now use the sub-domain DB

I'm not interested in migrations on the Master DB, but I do want it working on the sub-domains.

This is the best I've found so far, but I wonder if there is a more streamlined way of doing it: https://www.reddit.com/r/dotnet/comments/2t2xlz/entity_framework_multiple_database_single/

Bob
  • 3,074
  • 11
  • 43
  • 62

2 Answers2

1

You will have to do the following steps

  1. Create a connection resolver that always looks up to the metadata for getting the contextual connection string

  2. In your db context, you will have to pass the connection string obtained in(1) as your entity connection

This way, always you have the connection string based on the domain.

HTH

Saravanan
  • 7,637
  • 5
  • 41
  • 72
0

I ended up doing the following, and it works with migrations and all:

  • Create master DB context, configuration and migrations.
  • Create sub-domain DB context, configuration and migrations.
  • On Application_Start migrate and initialize the master database.
  • Loop through each sub-domain in the master database and call migrate and initialize.
  • On Application_BeginRequest get the current sub-domain and set a context item with the sub-domain name.
  • Now the main part: In your sub-domain DB context, initialize the constructor with a method that will get the connection string from the master database based on the sub-domain name set in the context item.

Remember that you can only get the sub-domain when a request is sent and not before begin request. Any calls to the sub-domain context before Application_BeginRequest is called will result in an error.

For your dependency injection into repositories, you can set the correct context being passed, so that it knows to used the master context or the sub-domain context.

Bob
  • 3,074
  • 11
  • 43
  • 62
  • nice, thanks, you use a redis cache for storange subdomain in application_beginrequest ? – Rod Jun 17 '15 at 01:22