After two days, I have finally managed to get it to work. I'm adding my solution here hoping that it might help someone in future.
Environment
- Azure API APP (but in theory, it should work for other types of projects too)
- SQL DB (hosted on Azure). It can be obviously any db
- EF 6.0 - Database First Approach
- Connection String is stored on Azure under Application Settings ->Connection Strings section. Image shown below
What I wanted to do
I wanted to put my connection string on Azure and like @Sandrino Di Mattia mentioned, dynamically retrieve it from there.
Steps which worked for me
- Create a connectionStrings in the web.config
`
<connectionStrings>
<add name="dbConnectionStringForAzure" connectionString="Local Connection String" providerName="System.Data.EntityClient"/>
</connectionStrings>
`
Note that the providerName is System.Data.EntityClient and not System.Data.SqlClient.
Extra bit: Also, once you have published the project, you can verify that the connection string in the web.config. Navigate to projectorapiurl.scm.azurewebsites.net.
Go to Menu -> Debug Console -> PowerShell -> Edit Web.config file.
(There are other ways to get the web.config files too. Use the one you prefer.)
Note: Here you might find another auto generated connection string by Azure. It's safe to remove that as we aren't using that.
Go to Azure -> your project and Application Settings. Add the details like shown below:
Name = dbConnectionStringForAzure
Value = Provider=System.Data.SqlClient; metadata=res://*/csdlModel.csdl|res://*/ssdlModel.ssdl|res://*/mslModel.msl; Provider Connection String ='Data Source=server.database.windows.net,1433;initial catalog=database;User ID=username;Password=password;MultipleActiveResultSets=True;App=EntityFramework;'
Front the third dropdown, select CUSTOM. It's important else Azure will add System.Data.SqlClient (or any other provider depending upon what is selected) in the provider name of our connection string, which we don't want.
- Save
At this stage, Azure should use this connection string on runtime. Want to verify!? do similar to what is suggested above by @Sandrino Di Mattia or in this SO post by @Shaun Luttin Retrieve the connection string of an SQL Azure database that is linked to a Windows Azure Web Site with C#.NET.
Alternatively, put the below code in any razor template:
<p>Value of dbConnectionStringForAzure :
@System.Configuration.ConfigurationManager.ConnectionStrings["dbConnectionStringForAzure"].ConnectionString
</p>
On the other hand, I have set the connection string name in my DbContext constructor.
public MyEntities() : base("name=dbConnectionStringForAzure")
{
}
Now, when I made a call to my API it dynamically used the connection stored in Azure.
Thanks to the dozens of posts and extra shots of coffee!