在实体框架中,如何通过代码更改数据库连接字符串

问题描述 投票:0回答:2

我需要更改我的代码,因为我在 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=&quot;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&quot;" providerName="System.Data.EntityClient" />
c# entity-framework mysql-connector
2个回答
0
投票

在代码中搜索

UseMySQL
。更改传递给该方法的字符串(它是连接字符串)。


0
投票

就是我想的最简单的。我必须输入这段代码:

 base(ConfigurationManager.ConnectionStrings["conn"].ConnectionString)

来自配置管理器的连接字符串从 web.config 而不是 app.config 获取它

© www.soinside.com 2019 - 2024. All rights reserved.