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

前端 未结 3 708
暗喜
暗喜 2021-01-18 05:31

I\'m experimenting some difficulties trying to use Connection String Builders (ADO.NET) within LINQ to SQL. Let me show you guys what I\'m trying to do:

相关标签:
3条回答
  • 2021-01-18 05:57

    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);
     } }
    
    0 讨论(0)
  • 2021-01-18 06:02

    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.

    0 讨论(0)
  • 2021-01-18 06:03

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

    Example:

    LINQTOSQLDataClassDataContext db = new LINQTOSQLDataClassDataContext(builder.ConnectionString);
    
    0 讨论(0)
提交回复
热议问题