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
- Edit config file
- 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.
In other way, you can change connection string is open
DBML file and right click then select Properties
In properties tab create on Connection and click on Connection String
In connection properties dialog box you can change the connection so the connection string.
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.
You can pass server name to this function to create connection string
and use output of this function in constructor of DataContext
So here you can pass any server name to create DataContext as of server.
For reference code is as below ,
01 | static string GetConnectionString( string serverName) |
04 | System.Data.SqlClient.SqlConnectionStringBuilder builder = |
05 | new System.Data.SqlClient.SqlConnectionStringBuilder(); |
06 | builder[ "Data Source" ] = serverName; |
07 | builder[ "integrated Security" ] = true ; |
08 | builder[ "Initial Catalog" ] = "Sample2" ; |
09 | Console.WriteLine(builder.ConnectionString); |
10 | Console.ReadKey( true ); |
11 | return builder.ConnectionString; |
I hope this post was useful. Thanks for reading.
No comments :
Post a Comment