且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在MVC 4上管理多个数据库

更新时间:2023-01-01 11:44:42

你是什么正在处理的是多租户。与您的问题没有直接关系,但这是一本关于多租户环境中***实践的好书。



http://msdn.microsoft.com/en-us/library/ff966499.aspx [ ^ ]



回复你问题,我不认为为各种租户维护静态连接字符串是个好主意。可能你明天可以有10个甚至100个租户。



我的建议是实现一个ConnectionStringManager类,它可以为你提供特定客户端的连接字符串。
What you are dealing with is Multi Tenancy. Not directly related to your question, but here is a good book on best practices in multi tenant environment.

http://msdn.microsoft.com/en-us/library/ff966499.aspx[^]

Coming back to you question, I don't think it's a good idea to maintain static connection strings for various tenants. Potentially, you can have 10 or even 100 tenants tomorrow.

My suggestion would be do implement a ConnectionStringManager sort of class which can give you the connection string for a specific client.


Configuration config = WebConfigurationManager.OpenWebConfiguration("~");
            ConnectionStringsSection section = config.GetSection("connectionStrings") as ConnectionStringsSection;
            var connection = WebConfigurationManager.ConnectionStrings["ClientConnection"].ConnectionString;
            string[] conn = connection.Split(';');
            string dataSource = conn[0];
            string initialCatalog = conn[1];
            string persistentSecInfo = conn[2];
            string userID = conn[3];

            string dbName=initialCatalog.Substring(16,9);

            if (!dbName.Equals(officeID))
            {
                connection = connection.Replace(dbName, officeID);
                section.ConnectionStrings["ClientConnection"].ConnectionString = connection;
                config.Save();
            }





这是我用来根据officeID更改连接的代码(指代客户端的数据库名称) ),我将初始目录的值替换为指向我需要的数据库。



有任何建议或意见吗?



This is the code I use to change my connection based on the officeID (which refers to the client's database name), I replace the value of the Initial Catalog to point to the database I need.

Any suggestions or comments?