[英]How to assign password to ConnectionString programatically
I have ConnectionString
defined in App.config
file and I check the option not to include sensitive data so the password is left out from the connection string.我在
App.config
文件中定义了ConnectionString
并检查了不包含敏感数据的选项,因此密码从连接字符串中省略了。 In the application code I'm using Entity Framework and I'm accessing the db like this:在我使用实体框架的应用程序代码中,我正在像这样访问数据库:
using (var db = new Entities())
{
List<DATA> d = db.DATA.ToList();
}
I want authenticate user by the DB password - user enters it when the application launches.我想通过数据库密码对用户进行身份验证 - 用户在应用程序启动时输入它。 The question is, how to add this password to the connection string when I don't handle the
ConnectionString
manually in the code?问题是,当我不在代码中手动处理
ConnectionString
时,如何将此密码添加到连接字符串中?
The farther I got is this:我得到的更远的是:
ConnectionStringSettings conn = ConfigurationManager.ConnectionStrings["Entities"];
EntityConnectionStringBuilder entityBuilder = new EntityConnectionStringBuilder(conn.ConnectionString);
SqlConnectionStringBuilder sqlBuilder = new SqlConnectionStringBuilder(entityBuilder.ProviderConnectionString);
sqlBuilder.Password = "pwd";
entityBuilder.ProviderConnectionString = sqlBuilder.ToString();
ConnectionStringSettings newConn = new ConnectionStringSettings("Entities",entityBuilder.ConnectionString);
But this still does not work and I cannot assing the new connection string to the ConfigurationManager.ConnectionStrings
- it says it is read only value.但这仍然不起作用,我无法将新的连接字符串分配给
ConfigurationManager.ConnectionStrings
- 它说它是只读值。 How to overcome this?如何克服这一点?
You can't assign ConfigurationManager.ConnectionStrings
because that just reflects your App.config
, which your app can't change.您不能分配
ConfigurationManager.ConnectionStrings
因为这只是反映了您的App.config
,您的应用程序无法更改。
But you can tell the EF which connection string to use:但是你可以告诉 EF 使用哪个连接字符串:
using (var db = new Entities(entityBuilder.ToString()))
{
List<DATA> d = db.DATA.ToList();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.