Single website multiple databases, database switching

前端 未结 2 1923
长情又很酷
长情又很酷 2020-12-18 12:04

I have created a content management system (CMS) for my company’s product databases. The CMS is based on asp.net scaffolding with many custom pages and actions mixed in. We

相关标签:
2条回答
  • 2020-12-18 12:26

    Create another database for user to database mapping. The structure would be like so:

    database UserMap 
    
        table Users
           username (composite primary key)
           dbID (composite primary key, foreign key to "Databases" table)
    
        table Databases
           dbID (primary key)
           connectionString
    

    Then,

    1. populate the list of database in table "Databases"
    2. Do your SQL work to copy the users from the other websites into this "UserMap" database
    3. Write a trigger in each CMS database to add or remove a user as they are created or removed in their respective CMS so it updates the "UserMap" database
    4. Modify your code on the CMS(s) to use this single database for lookup to what connection string should be used.

    This would allow you to rely on the single database for the lookup and switch between them in a managed fashion going forward. It requires some up front work but after the triggers are there, you don't have to do anything more.

    0 讨论(0)
  • 2020-12-18 12:39

    Assuming that your database structures are identical, you could use a factory method anywhere you get an instance of your entity context and put logic in there to grab the correct connection string (or calculate it if there's a naming convention that you could use). Something like this might work for example:

        public static MyDatabaseEntities CreateEntityContext(string productName)
        {
            string connectionString = null;
            switch (productName.Trim().ToLower())
            {
                case "apples":
                    connectionString = ConfigurationManager.ConnectionStrings["MyDatabase_Apples"].ConnectionString;
                    break;
                case "pears":
                    connectionString = ConfigurationManager.ConnectionStrings["MyDatabase_Pears"].ConnectionString;
                    break;
                default:
                    connectionString = ConfigurationManager.ConnectionStrings["MyDatabase"].ConnectionString;
                    break;
            }
            return new MyDatabaseEntities(connectionString);
        }
    

    Then use this method anywhere you need an instance of your CRM data context passing in the product name that you've calculated on your landing page.

    0 讨论(0)
提交回复
热议问题