Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ to SQL connectionstring

I have an application that I want to be able to configure the connection string for my LINQ to SQL. I've tried so many different ways but cannot seem to get it working. I want to do this dynamically in the code when the app is run, the reason for this is that the user can change the connection settings.

If I delete the connectionString out of app.config the application still works OK (communicating) which makes me wonder where I should be changing the connection string?

like image 336
Prisoner Avatar asked Feb 21 '11 17:02

Prisoner


3 Answers

I think that the best way to do it is a combination of Albin's and Rup's answers. Have a value in the config file, and then read it at run time 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 on the running program.

like image 190
Francisco Noriega Avatar answered Oct 17 '22 04:10

Francisco Noriega


You can pass an override connection string into the DataContext constructor:

var db = new MyDataContext("Data Source=Something Else;")
like image 24
Rup Avatar answered Oct 17 '22 03:10

Rup


The DBML class (YourDataContext) has an overloaded constructor which takes ConnectionString, so try instantiating that instead of the default one.Get the connection string from app.config and use that to create the instance.

YourDataContext context = new  YourDataContext (ConfigurationManager.ConnectionStrings["ConnStringInAppConfig"].ConnectionString)
like image 25
Jobi Joy Avatar answered Oct 17 '22 03:10

Jobi Joy