How can I make LINQ to SQL use a connection string which is being modified at runtime?

老子叫甜甜 提交于 2019-12-01 16:31:50
CleverCoder

It seems like you are trying to modify the connection string that is stored in the app.config file. When you use a no argument constructor for your data context, it reads what was configured at design time.

Try injecting your modified connection string into the constructor of the DataContext:

ConnectionStringSettings settings = ConfigurationManager.ConnectionStrings["LoremIpsum"];
SqlConnectionStringBuilder builder;
LINQTOSQLDataClassDataContext db;

if (null != settings) 
{   
    string connection = settings.ConnectionString;  
    builder = new SqlConnectionStringBuilder(connection);

   // passwordTextBox being the control where joe the user actually enters his credentials

    builder.Password =passwordTextBox.Text;  
    db = new LINQTOSQLDataClassDataContext(builder.ConnectionString);
 } }
Ostemar

You're forgetting to send in the connectionstring to the DataContext constructor.

Example:

LINQTOSQLDataClassDataContext db = new LINQTOSQLDataClassDataContext(builder.ConnectionString);

You can force a DataContext to use a specific connection string with

DataContext db = new DataContext(myConnectionString);

The parameterless DataContext constructor will use a connection string from the App.config file first, then the connection string set at compile time.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!