How to refer to multiple SQL Server databases in app.config connection string - sql-server

I am running SQL Server unit tests and have two test databases on which I want to test, "A" and "B". In my VSTS Release definition, I deploy my DACPAC files for both of these test DBs to the same server. In my app.config file that is copied to the build output, I have the following connection string, which references database "A" as the "Initial Catalog":
<SqlUnitTesting>
<DataGeneration ClearDatabase="true" />
<ExecutionContext Provider="System.Data.SqlClient" ConnectionString="Data Source=XYZ;Initial Catalog=A;Integrated Security=True;Pooling=False"
CommandTimeout="30000" />
<PrivilegedContext Provider="System.Data.SqlClient" ConnectionString="Data Source=XYZ;Initial Catalog=A;Integrated Security=True;Pooling=False"
CommandTimeout="30000" />
</SqlUnitTesting>
If I also want to connect to database "B", how can I do this?
Could I create two Initial Catalogs in the same connection string?
Could I create two configSections, where one has the connection string refer to "A" and the other refers to "B"?
Could I remove Initial Catalog from my connection string so that it does not only limit me to "A"?
Could I create two app.config files and have them in the same location?
Thank you.

Answering my own question. I learned that each project has its own app.config, and when the projects build, they are outputted as .dll.config files. In each one of those, I specify the same server, but I use the different databases as the Initial Catalog values. By doing this, each project looks at its respective .dll.config and the db connections are successfully established.

Related

Cannot attach the file ".mdf" as database "aspnet-"

I'm using web sockets and SqlDependency to build a game server. An error with the SqlDataReader indicated that I should call SqlDependency.Start. I included the following in my Global.Asax:
SqlDependency.Start(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
This line always ends with the SqlException, with message:
Cannot attach the file 'C:...aspnet-ProjectName-11111111111.mdf' as database 'aspen-ProjectName-11111111111'.
I've been trying to fix this for two days. I've started a fresh MVC 4 WebAPI app, with a basic model, context, and seed, and can't get around this error. I've tried the various solutions in the following:
https://social.msdn.microsoft.com/Forums/en-US/ae041d05-71ef-4ffb-9420-45cbe5c07fc5/ef5-cannot-attach-the-file-0-as-database-1?forum=adodotnetentityframework
ASP.NET MVC4 Code First - 'Cannot attach the file as database' exception
EF5: Cannot attach the file ‘{0}' as database '{1}'
No change. I'm running MVC4 API in Visual Studio 2012, SQL Server is 2014.
This is a DB connection problem, right? The .mdf file in my AppData folder (both it and the log file are there in both projects) can't be connected to SQL Server? Also, help?
I encountered the same problem as you.
In your Web.config file, find you connection string, copy and paste it and then remove everything after the 'MultipleActiveResultSets' - apart from the providerName.
So in mine, it changed from this:
<add name="ApplicationName" connectionString="Data Source=(localdb)\MSSQLLocalDB; Initial Catalog=ApplicationNameContext-20151023111236; Integrated Security=True; MultipleActiveResultSets=True; AttachDbFilename=|DataDirectory|ApplicationNameContext-20151023111236.mdf" providerName="System.Data.SqlClient" />
Became this:
<add name="NotificationConnection" connectionString="Data Source=(localdb)\MSSQLLocalDB; Initial Catalog=ApplicationNameContext-20151023111236; Integrated Security=True;" providerName="System.Data.SqlClient" />
And as you will notice the connection has a different name.
The connections will still query the same database.
Now modify your connection string name in the Dependency.Start parameter to be your the name of the connection string you just created:
SqlDependency.Start(ConfigurationManager.ConnectionStrings["NEW_CONNECTION_NAME"].ConnectionString);
Remove the Initial Catalog property in your connection string.
You should see this answer: https://stackoverflow.com/a/20176660/161471

Azure: The context is being used in Code First mode with code that was generated from an EDMX

I have MVC app running fine in local. After updating to Azure, it started throwing the error:
The context is being used in Code First mode with code that was generated from an EDMX file for either Database First or Model First development. This will not work correctly. To fix this problem do not remove the line of code that throws this exception. If you wish to use Database First or Model First, then make sure that the Entity Framework connection string is included in the app.config or web.config of the start-up project.
I have checked if there is any difference between the local web.config and azure web.config. except the credentials, everything is same. And it read:
<add name="DBEntities"
connectionString="metadata=res://*/DBModel.csdl|res://*/DBModel.ssdl|res://*/DBModel.msl;
provider=System.Data.SqlClient;
provider connection string="data source=xx;initial catalog=xx;persist security info=True;user id=xx;password=xx;MultipleActiveResultSets=True;application name=EntityFramework""
providerName="System.Data.EntityClient" />
I am using EF 6.1.3, MVC5
I ran into the same error message and managed to solve it with the help of this post here on StackOverflow.
In the Azure Management / Web Apps / [Your web app] / CONFIGURE / connection strings , make sure of 3 things :
The connection string has the same name as the connection string in your project.
The connection string Value contains all of the metadata as appears in the connection string in your project. Mine looks like this:
metadata=res://\*/Models.[MyModel].csdl|res://\*/Models.[MyModel].ssdl|res://\*/Models.[MyModel].msl;provider=System.Data.SqlClient;provider connection string="Server=tcp:[myDBServer].database.windows.net,1433;Database=[myDB];User ID=[myDBUser]#[myDBServer];Password=[myPassword];Trusted_Connection=False;Encrypt=True;Connection Timeout=30;"
The third column (default set to SQL Database) is set to Custom
Found a simpler solution than adding all the stuff in the Azure connection string. I just changed the connection string name in Azure. It worked..
I had to deal with the same issue. The solution was
Connect to the website by FTP
Edit web.config
Add following connection string:
add name="NewDatabaseEntities" connectionString="metadata=res:///NewDatabase.csdl|res:///NewDatabase.ssdl|res://*/NewDatabase.msl;provider=System.Data.SqlClient;provider connection string="Data Source=tcp:your.database.windows.net,1433;initial catalog=your;integrated security=False;User Id=your;Password=your;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient"
Thanks Microsoft for poorly documentation of EntityFramework Database First on Azure.
You need to change this line metadata=res:///NewDatabase.csdl|res:///NewDatabase.ssdl|res://*/NewDatabase.msl;
to
metadata=res://*/;

Parallels Plesk Panel connecting to database server connection string

I am using Entity Framework to access the data from my database. It's an MVC application and works fine locally. When I deploy the application on hosting (Parallels Plesk Panel, MS hosting) I get problems with accessing the SQL server instance. There are options in the cPanel which hold connection strings.
LocalSqlServer:
data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true
xContainer:metadata=res:///Models.x.csdl|res:///Models.x.ssdl|res://*/Models.x.msl;provider=System.Data.SqlClient;provider connection string=
When I upload the site xContainer is generated alone. I found the sql server's instance name and applied it to the data source. In my web.config file I am using the the xContainer. The code after this paragraph is what it seems logic to me to add after the connection string= in the xContainer.
I have tried this with various properties. Data source, initial catalog, and the other info are filled into the conn string (here I am showing only /).
Data Source=x;Initial Catalog=/;Persist Security Info=True;User ID=/;Password=/;MultipleActiveResultSets=True providerName=
The error I receive is that the sql server instance cannot be found. If I add the last piece of code to the container it tells that I don't have a providerName, After adding a providerName the string is deleted to the starting xContainer string:
metadata=res:///Models.x.csdl|res:///Models.x.ssdl|res://*/Models.x.msl;provider=System.Data.SqlClient;provider connection string=
The error I receive is that the **sql server instance cannot be found**.
So, what is the SQL instance name? :)
it maybe not ".\SQLEXPRESS" but ".\SQLEXPRESS2012" or even ".\MSSQLSERVER" or anything else.
You will need to Edit the Web.Config file manually. The ASP.NET Settings page will remove the providerName.
An example of a connection string using EntityClient is below. You can remove the metadata information if you're not using an Entity Model. You will notice the providerName is outside of the actual connectionString and is the reason you will need to edit the file manually.
connectionString="metadata=ModelInformation;provider=System.Data.SqlClient;provider connection string="data source=IP;initial catalog=DATABASE;User ID=USERNAME;Password=PASSWORD;multipleactiveresultsets=True;application name=EntityFramework"" providerName="System.Data.EntityClient"

External SQL Server access in MVC 3 + Entity Framework for query-only

I'm devoloping a system using MVC 3 with EF 4. In this system, I need to lookup some information that already exists in an external database.
Saving me project's information on my database is OK. I defined my Models on it and let DbContext create the tables on my server.
The problem is when I try to query some data from the external database. I've added the connection string in the properly place on Web.config:
<connectionStrings>
<add name="ExtDBConnectionString" connectionString="Data Source=path.to.server;Initial Catalog=DBName;Persist Security Info=True;User ID=user;Password=pass;Pooling=True;Min Pool Size=5;Max Pool Size=60;Connect Timeout=2;" providerName="System.Data.SqlClient" />
</connectionStrings>
Is it possible to just create some queries to this server on my project without the overload of recreating all the Models from this external database? I know I can recover this connection string on my code by using the command System.Configuration.ConfigurationManager.ConnectionStrings["ExtDBConnectionString"].ConnectionString, but how can I create a connection and instantiate my queries?
Thanks in advance!
Edit: #rouen called my atention I didn't explicitly said the databases are differents. They do not share the same schema! The external database is the output of a report; so, I need to traverse it on my project to import the relevant lines to the local database.
I would just use standard ADO.NET. Use the SqlConnection and SqlCommand classes.
ADO.NET Examples on MSDN:
http://msdn.microsoft.com/en-us/library/dw70f090.aspx
Is the remote database schemantically identical as your local ? If yes, you can pass connectionstring to constructor of ObjectContext/DbContext, and it will use that database.
http://msdn.microsoft.com/en-us/library/gg679467%28v=vs.103%29.aspx

Microsoft Enterprise Library - How to create database based on Type

I'm using Enterprise Library 4.1.
I have a new feature to implement and it requires the use of mysql.
I have found Enterprise Library Contrib, which adds functionalities to use MySQL with Enterprise Lib.
Works great.
To get it to work, you need to call the method 'DatabaseFactory.CreateDatabase(connectionStringName);' like you would normally do. The connection string name is stored in the configuration and linked to the database provider mapping configuration section.
As an exemple:
<dataConfiguration defaultDatabase="MyDefaultDb">
<providerMappings>
<add databaseType="EntLibContrib.Data.MySql.MySqlDatabase, EntLibContrib.Data.MySql, Version=4.1.0.0, Culture=neutral, PublicKeyToken=null"
name="MySql.Data.MySqlClient" />
</providerMappings>
</dataConfiguration>
<connectionStrings>
<add name="MyDefaultDb"
connectionString=""
ProviderName="System.Data.SqlClient" />
<add name="acb_leaderboards"
providerName="MySql.Data.MySqlClient"
connectionString="" />
</connectionStrings>
Unfortunately, my application will connect to multiple MySQL database and the conncetion will vary from time to time. I can't have the mysql connection string be specified in the configuration.
I want to create a MySQL database object based on the providerMapping configuration.
How can I do that?
Thank you.
PS.
English is not my first language, I'm trying my best.
If you know ahead of time that you're using MySql, and assuming that the MySqlDatabase class follows the same patterns as the Database classes in the core Entlib, then you can just new it up directly, you don't have to go through the factory method.
Database mySql = new MySqlDatabase(currentConnectionString);
should just work. You only need to go through the factory if you're pulling named connection strings from config.

Resources