LINQ to SQL connectionstring

I have an application that I want to configure for the connection string for my LINQ to SQL. I tried so many different ways, but couldn't make it work. I want to do this dynamically in the code when the application starts, the reason is that the user can change the connection settings.

If I remove connectionString from app.config, the application is still working fine (communicating), which makes me wonder where should I change the connection string?

+6
source share
6 answers

I think the best way to do this is by combining the answers of Albin and Rup. Make a difference in the configuration file, and then read it at runtime and feed it to the context constructor, something like this:

Web.config:

<appSettings>
<add key="ConString" Value="The connection string" />

CODE:

//read value from config
var DBConnString = System.Configuration.ConfigurationManager.AppSettings("ConString");

//open connection
var dataContext= new MyDataContext(sDBConnString)

this way you can change the connection string even at runtime, and it will work and change in the current program.

+9
source

You can pass an override string to the DataContext constructor :

var db = new MyDataContext("Data Source=Something Else;")
+8
source

DBML (YourDataContext) , ConnectionString, , , one.Get app.config .

YourDataContext context = new  YourDataContext (ConfigurationManager.ConnectionStrings["ConnStringInAppConfig"].ConnectionString)
+2

app.config. , , , LINQ2SQL , DBML. app.config, .

0

public dbDataContext() : 
            base(global::invdb.Properties.Settings.Default.Enventory_4_0ConnectionString, mappingSource)
    {
        OnCreated();
    }

//Original 
public string Enventory_4_0ConnectionString {
            get {
                return ((string)(this["Enventory_4_0ConnectionString"]));
            }
        } 

this

//Modified code
public string Enventory_4_0ConnectionString {
            get {
                return (System.Configuration.ConfigurationManager.ConnectionStrings["Enventory_4_0ConnectionString"].ConnectionString);
            }
        }
0

dbml designer.cs . , dev prod, web.config ;

    public HallLockerDataContext() : 
            base(ConfigurationManager.ConnectionStrings["MYDB1"].ConnectionString, mappingSource)
    {
        OnCreated();
    }

:

    using (var db = new HallLockerDataContext())
    {

    }
0

All Articles