如何以编程方式将密码分配给 ConnectionString
我在 App.config
文件中定义了 ConnectionString
,并选中了不包含敏感数据的选项,以便在连接字符串中省略密码。在应用程序代码中,我使用实体框架,并且像这样访问数据库:
using (var db = new Entities())
{
List<DATA> d = db.DATA.ToList();
}
我想通过数据库密码对用户进行身份验证 - 用户在应用程序启动时输入它。 问题是,当我不在代码中手动处理 ConnectionString
时,如何将此密码添加到连接字符串中?
我得到的进一步是这样的:
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);
但这仍然不起作用,我无法将新的连接字符串分配给 ConfigurationManager.ConnectionStrings
- 它说它是只读值。如何克服这个问题?
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. 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?
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. How to overcome this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您无法分配
ConfigurationManager.ConnectionStrings
,因为它仅反映您的App.config
,而您的应用无法更改它。但您可以告诉 EF 使用哪个连接字符串:
You can't assign
ConfigurationManager.ConnectionStrings
because that just reflects yourApp.config
, which your app can't change.But you can tell the EF which connection string to use: