我需要更改我的代码,因为我在 web.config 中有连接字符串。我从一个项目中打电话。我不想使用app.config。我需要在 web.config 中进行集中化。
如何通过代码更改或打开实体框架的连接?主要项目是使用框架 4.6.1 的 mvc 5。
我正在使用 MySQL 数据库。
我正在使用此代码来更改数据库:
string conn = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
((IObjectContextAdapter)db).ObjectContext.Connection.ChangeDatabase(conn);
我的连接字符串是:
<add name="conn" connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=MySql.Data.MySqlClient;provider connection string="server=xxx.xxx.xxx.xxx;Max Pool Size=1000;MinimumPoolSize=5;ConnectionReset=true;ConnectionLifeTime=0;user id=xxx;port=3306;password=xxx;SSL Mode=none;persistsecurityinfo=True;AllowPublicKeyRetrieval=true;Convert Zero Datetime=True;database=xxx"" providerName="System.Data.EntityClient" />
在代码中搜索
UseMySQL
。更改传递给该方法的字符串(它是连接字符串)。
就是我想的最简单的。我必须输入这段代码:
base(ConfigurationManager.ConnectionStrings["conn"].ConnectionString)
来自配置管理器的连接字符串从 web.config 而不是 app.config 获取它