Connection string in LINQ

It is very common that you come across scenario when at run time you need to change the database server and so the connection string is used in your LINQ. This may come as requirement, if you are moving your application from dev server to staging and from staging to production.

There are two ways you can change connection string on fly

  1. Edit config file
  2. Build connection string to pass as constructor of DataContext.

Edit config file

You can do it in two ways. Open the configuration file and edit connection string here.

clip_image002

In other way, you can change connection string is open DBML file and right click then select Properties

clip_image002[5]

In properties tab create on Connection and click on Connection String

clip_image004

In connection properties dialog box you can change the connection so the connection string.

clip_image006

Editing Connection String in code

Assuming you is creating a function to return connection string. Crete function that it takes server name as input parameter. Your function should be like below.

clip_image008

You can pass server name to this function to create connection string and use output of this function in constructor of DataContext

clip_image010

So here you can pass any server name to create DataContext as of server.

For reference code is as below ,

 static string GetConnectionString(string serverName)
        {

            System.Data.SqlClient.SqlConnectionStringBuilder builder =
                           new System.Data.SqlClient.SqlConnectionStringBuilder();
            builder["Data Source"] = serverName;
            builder["integrated Security"] = true;
            builder["Initial Catalog"] = "Sample2";
            Console.WriteLine(builder.ConnectionString);
            Console.ReadKey(true);
            return builder.ConnectionString;

        }

I hope this post was useful. Thanks for reading.  Smile

Add to FacebookAdd to DiggAdd to Del.icio.usAdd to StumbleuponAdd to RedditAdd to BlinklistAdd to TwitterAdd to TechnoratiAdd to Yahoo BuzzAdd to Newsvine

2 responses to “Connection string in LINQ”

  1. Really this is a good article, which helps a lot to understand the connection string for beginners as me as well as developer. i had found another nice post on connection string which is also having a wonderful explanation on connection string, for more details check out this link…

    http://mindstick.com/Articles/d49d88a2-5a67-426f-87a0-00e16bd04f62/?Connection%20Strings

    Thanks everyone for your precious post.

Leave a comment

Create a website or blog at WordPress.com