如何以编程方式为Connection String分配密码

时间:2011-06-08 13:08:13

标签: c# .net entity-framework connection-string

我在ConnectionString文件中定义了App.config,并且我选中了不包含敏感数据的选项,因此密码是从连接字符串中省略的。在应用程序代码中,我正在使用Entity Framework,我正在访问数据库,如下所示:

using (var db = new Entities())  
{                
     List<DATA> d = db.DATA.ToList();
}

我想通过DB密码验证用户 - 用户在应用程序启动时输入它。 问题是,当我不在代码中手动处理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 - 它说它是只读值。如何克服这个?

1 个答案:

答案 0 :(得分:3)

您无法分配ConfigurationManager.ConnectionStrings,因为这只会反映您的应用无法更改的App.config

但是你可以告诉EF使用哪个连接字符串:

using (var db = new Entities(entityBuilder.ToString()))  
{                
     List<DATA> d = db.DATA.ToList();
}