Saturday, 3 May 2014

Add Dynamic Connection String in EntityFramework.

Create a method 'GetSqlConnectionString()' in the class file or code-behind.


Public static string GetSqlConnectionString()
{
var servername=@" "+ConfigurationManager.Appsetting["ServerName"];//is getting from app-code
var databasename=ConfigurationManager.Appsetting["DatabaseName"];
var username=ConfigurationManager.Appsetting["UserName"];
var password=ConfigurationManager.Appsetting["Password"];
SqlConnectionStringBuilder connection=new SqlConnectionStringBuilder();
connection.DataSource=servername;
connection.InitialCatalog=databasename;
connection.UserID=username;
connection.Password=password;
connection.UserInstance=true;
var connectionbuilder=new EntityConnectionStringBuilder();
connectionbuilder.Provider="System.Data.Source";
connectionbuilder.ProviderConnectionString=connection.ToString();
connectionbuilder.metadata=string.Format("res://{0}/yourdatabae.csdl|res://{0}/yourdatabase.ssdl|res//{0}/
yourdatabase.msdl";typeof(yourdatabaseEntities):Assembly.FullName);

return connectionbuilder.ToString();
}





Here you can call the function and get the connectionstring

string constr=GetSqlConnectionString();
using(MyEntities entity=new MyEntities(constr))
{
//here you can use the table,procedure etc.
}

Have any doubts then comment it.

No comments:

Post a Comment