views:

337

answers:

2

I have an application that works with a database "TestDB". At the time I was developing the application I was using linq to sql and adding my data tables by dragging and dropping to the TestDB.dbml file and probably .net automatically sets the connection string to the local sql server on my machine. The application is supposed to launch on some windows based instruments. and the database will be local in those instruments.

Now, how can I change the connection string to make sure that the local database inside the instrument will be targeted for my application?

Also, I added username and password to my database so it will not be windows Authentication connection and my guess is that username and password should be part of the connection string.

A: 

If you set Data Source = localhost in the connection string, it should always reference the local machine and will save you from having to set it individually for each machine running the app.

Edit: Just as an FYI, check out http://connectionstrings.com/, it's quite handy.

Frank Tzanabetis
A: 

When you create your DataContext in your code you will pass in the ConnectionString. So you can store that in a config file and then using ConfigurationManager grab the ConnectionString and use it to create your DataContext like so:

public class SomeService
    {
        private SomeDataContext _db = null;

        public SomeService() 
        {
            _db = new SomeDataContext(ConfigurationManager.ConnectionStrings["SomeSqlServer"].ConnectionString);
        }

        public SomeService(string connectionString)
        {
            _db = new SomeDataContext(connectionString);
        }

        public SomeDataContext DB
        {
            get
            {
                return _db;
            }
        }

        // whatever methods you want to use that access this DataContext
}
Jeff T
Thank you for your response. I had my connection string in the app.config file as the address of my local database and when I had "TestDataContext db=new TestDataContext()"line in my application, I was not passing the connection string and it was working fine. Now, can you please explain more on the configuration manager? My guess is that it will automatically get the server location independent of the device. so it dynamically changes when the application starts to run on different devices and that is what I need. Please correct me if I am wrong.regards,
Hasti
Also when I run this code I get a null reference exception. I think it is related to the app.config file. Thank you for the help
Hasti