I'm adding an SQL database to my Azure API App. I have an empty SQL database which I created separately via portal.azure.com. My problem is I don't know how to set up the connection string so that my app uses the Azure database.
I have followed the Code First Migrations article, but I'm stuck on the deployment phase. I cannot see any connection configuration in any of the files in the project.
How do I set the connectionString to be used by the app when it's deployed in Azure?
More info:
To be precise, I can see 2 things:
Commented out connectionStrings sections in Web.Debug/Release.config files.
Some EF configuration in Web.Config:
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="mssqllocaldb" />
</parameters>
</defaultConnectionFactory>
(...)
When I execute tests locally I can see Database.Connection.ConnectionString is
Data Source=(localdb)\mssqllocaldb;Initial Catalog=XDataAPI.Models.MyContext;Integrated Security=True;MultipleActiveResultSets=True
BTW. The publish window states that no database have been found in the project. (This doesn't really bother me, it's a secondary issue)
Edit:
DbContext, as requested:
public class MyAppContext : DbContext
{
public DbSet<Organisation> Organisations { get; set; }
}
Pass in the connection name as param to your constructor, and then use the same connection name when setting up your connection string in your web.config, like this:
public class MyAppContext : DbContext
{
public MyAppContext():base("MyConnectionName"){}
public DbSet<Organisation> Organisations { get; set; }
}
And then, in web.config:
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<connectionStrings>
<add name="MyConnectionName" connectionString="Server=tcp:test.database.windows.net,1433;Database=testdb;User ID=test#test;Password=p4ssw0rd!;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;"
providerName="System.Data.SqlClient" />
</connectionStrings>
....
<configuration>
If you want to run from a local machine, remember that you need to allow incoming connections from your IP on your Azure database server firewall.
If you set up the SQL Server VM, then
<add name="DataContext" connectionString="Data Source=VMname.cloudapp.net; Initial Catalog=catalog; User ID=login;Password=password; MultipleActiveResultSets=True;" providerName="System.Data.SqlClient" />
If you set up the SQL Azure, then that tutorial should be used.
As for the connection string place, please refer to some documentation. You use LocalDB, instead of that you should use the SQL Server.
You should be able to just update the connection string for your data context in the web.config to use you Azure SQL Database. For my testproject it is just at the top of web.config:
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<connectionStrings>
<add name="WebApplication4Context" connectionString="Server=tcp:test.database.windows.net,1433;Database=testdb;User ID=test#test;Password=p4ssw0rd!;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;"
providerName="System.Data.SqlClient" />
</connectionStrings>
....
<configuration>
Don't forget to also update the firewall settings of your Azure SQL Database Server to make it accessible for your application.
Edit: You can also change the database connection for just your Azure environment by adding the your Azure SQL DB in the Publish dialogue:
If the connection string is missing web.config, then it is using the default name which is DefaultConnection and it refers to the localdb instance that gets installed with SQL or SQL Express.
To configure it, you have to first create a SQL DB on Azure, from the Portal, create a new database and give it a name and make sure it exist in the same resource group and region to decrease the latency and improve the performance.
Open the created database and you will find the connection string for many platforms, copy the one for .Net and go to the Web App settings, you should find a place for connection strings, add a new one and name it DefaultConnection and add the value a the connection string you just copied from the database blade
When you run the application for the first time, code first will connect to the database and apply the migration if you specified that during the publish wizard which adds some configuration in web.config as well.
For .Net FW 4.5 or above:
1. Your DbContext class:
public class MyAppContext: DbContext
{
public MyAppContext() : base("YourConnectionStringKey") { }
public DbSet<Organization> Organizations{ get; set; }
}
2. Your Web.config:
<connectionStrings>
<add name="YourConnectionStringKey" connectionString="DummyValue" providerName="System.Data.SqlClient" />
</connectionStrings>
3. In your Azure WebApp settings, add the connection string (which will be automatically injected into your Web.config at runtime)
If you're not developing using the .Net framework, see https://azure.microsoft.com/en-us/blog/windows-azure-web-sites-how-application-strings-and-connection-strings-work/ for further details.
I am new to Postgres and I need help with connection string.
My app using Entity Framework. I have this connectionString to MSSQL Server:
<connectionStrings>
<add name="DBContext" connectionString="Data Source=localhost;Initial Catalog=DB;Integrated Security=True;MultipleActiveResultSets=True" providerName="System.Data.SqlClient" />
</connectionStrings>
to my project i download a npgsql package (http://pgfoundry.org/projects/npgsql/) a need to help with editing connection string to Postgres database.
How to set providerName to npgsql?
Thank for help
"don't hard code your providers" discusses this in detail.
It shows a setting like what you want:
<add name="blah" providerName="Npgsql"
connectionString="Server=127.0.0.1;Port=5432;Database=myDataBase;
User Id=myUsername;Password=myPassword;"/>
but then explains why you should not do this, you should read the settings from your application's configuration file at runtime instead.
I use Entity Framework Code First,
My connection string is in a configuration file:
<connectionStrings>
<clear/>
<add name="ApplicationServices" connectionString="Data Source=PC-X;Initial Catalog=MYdb;Integrated Security=True"/>
</connectionStrings>
When I try to access the data (something that should create the DB) is falling with the following error:
The connection string 'ApplicationServices' in the application's
configuration file does not contain the required providerName
attribute."
What am I missing?
You're missing the following piece of code after the connectionString attribute (assuming that you're using SQL):
providerName="System.Data.SqlClient"
Sometime in the future. the complete code
<add name="YouContext" connectionString="Integrated Security=True;Persist Security Info=False;Initial Catalog=YourDatabaseName;Data Source=YourPCName;" providerName="System.Data.SqlClient"/>
Go down in your web.config until you reach the providers tag.
For instance, here's my providers statement:
<providers><provider invariantName="System.Data.SqlClient" ... /></providers>
you should add this System.Data.SqlClient as a provider name in your connection string
so your connection string should look like this:
<connectionStrings>
<add name="ApplicationServices" providerName="System.Data.SqlClient" connectionString="Data Source=PC-X;Initial Catalog=MYdb;Integrated Security=True"/>
</connectionStrings>
In my case the problem was with an incorrect StartUp project target. In the PM console the target migration assembly project was correct.
I have a multiproject solution and the target was on some web-service project.
So I changed the StartUp to the main WebSite project and the migration have complited without errors.
I developed a web site on my local pc and local database using entity framework, Now I gave all the code to my client now the entity framework gives an error underlying provider failed on open I modified data source, initial catalog, user id and password of the connection string of entity framework but of no use please help. below is my connection string.
<add name="SBV_dbEntities" connectionString="metadata=res://*/SBVEntityModel.csdl|res://*/SBVEntityModel.ssdl|res://*/SBVEntityModel.msl;provider=System.Data.SqlClient;provider connection string="data source=.\SQLEXPRESS;initial catalog=yagnesh_db;user id=yagnesh;password=yagnesh#123;multipleactiveresultsets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
use like below.Give a connection string to the SQL server is as below (This is a sample code).
<add name="ContextName" connectionString="Data Source=ServerName;Initial Catalog=DBCatalogName;Integrated Security=True;MultipleActiveResultSets=True;App=EntityFramework"
providerName="System.Data.SqlClient" />
e.g.
<add name="PawLoyalty" connectionString="Server=.;database=PawLoyalty;Trusted_connection=true;pooling=true;MultipleActiveResultSets=True" providerName="System.Data.SqlClient" />
I hope this will help to you.
Can anyone suggest how I could programatically switch debug and live connection strings?
I've seen other people have passed an EntityConnection to the constructor from the controller like this :
private XYZDatabase db = new XYZDatabase(ConfigurationManager.
ConnectionStrings["XYZDatabase-TEST"].ConnectionString);
but it still requires manually changing it? is there a way to use
System.Net.Dns.GetHostName() or similar
to switch it automatically?
Thanks
Ayende has a post that addresses this issue.
http://ayende.com/blog/135169/frictionless-development-web-config-and-connection-strings
In my software I just have 2 connection strings of the same name in my app.config and comment/uncomment to switch between configurations.
Another method is that you could create a static property in your solution (.asax file?) and just use that to swap between XYZDatabase-TEST and XYZDatabase when you are fetching ConnectionStrings.
Add connection string to your Web.config like:
<connectionStrings>
<add name="XYZDatabase-TEST" connectionString="Server=.\SQLEXPRESS;Database=XYZDatabase-TEST";integrated security=SSPI;" providerName="System.Data.SqlClient" />
</connectionStrings>
Then open you Web.Release.config and add
<connectionStrings>
<add name="XYZDatabase-TEST"
connectionString="Data Source=OTHERSERVER;Initial Catalog=XYZDatabase-TEST;Persist Security Info=True;User ID=sa;Password=password" providerName="System.Data.SqlClient"
xdt:Transform="SetAttributes"
xdt:Locator="Match(name)"/>
</connectionStrings>
Now, everytime you will publish you application to deployment server using Release configuration it will use the connection string from web.release.config
Note that this transformation will not work locally when you debug. You must publish to run the web.config transformation.