Single DbContext using multiple connection strings per environment - c#

I know that currently a group of developers that I joined do not use Entity Framework, but they are fine with me using it.
Currently their connection strings are stored in web.config (or app.config)
<add name="LH_RPMDB"
connectionString="data source=localhostdb;Database=dbsim;user id=sim;password=sim;Application Name=SIM-LH;"
providerName="System.Data.SqlClient" />
<add name="DEV_RPMDB"
connectionString="data source=devdb;Database=dbsim;user id=sim;password=sim;Application Name=SIM-dev;"
providerName="System.Data.SqlClient" />
<add name="QA_RPMDB"
connectionString="data source=qadb;Database=dbsim;user id=sim;password=sim;Application Name=SIM-qa;"
providerName="System.Data.SqlClient" />
Now they are telling me to use LH for localhost, then upper environments will they fall in line with DEV and QA.
I'm NOT sure if they are "detecting" the URL for what server as I'm new to the team. I am just trying to get my DbContext in place to consume the proper database connection string.
Currently I just have 1 DbContext with one connection string and thus
public class RPMContext : DbContext
But I see that "they" are using code like this:
ws.Url = ConfigurationSettings.AppSettings(ConfigurationSettings.AppSettings("Environment") + "_SNTRAX")
However, I am wanting to leverage the several connection strings for all the environments with a single DbContext.
I found some code that shows this example web.config
<connectionStrings>
<add name="DefaultConnection"
connectionString ...
then
public TrackerContext() : base("Name=DefaultConnection") {}
another example I was seeing is
public partial class HOLDbEntities
{
public HOLDbEntities(string connectionString)
: base(connectionString)
Here is a stackoverflow article I had seen, it doesn't really get me to where I want to be though
Entity Framework - using the same DbContext with different connection strings
What do I want? Well I know that I need to have all the environments connection strings in the app.config (not using web.config with this project as it is a console application).
What I do not know is how to know what environment that I am in for the application to be somewhat dummy proof and just "automatically "work"
I'm thinking that reading the URL, but actually it is a console application So I wonder if per server environment if there should be an appsetting changed for which connection string to use so "LH" vs. "DEV" and "QA" and then a few others...
Thoughts?

Try the Configuration Extension perhaps?

Related

Get Azure connection string in datalayer

Someone thought, a long time ago, it was a good idea to add connections string hardcoded in the datalayer of our web api. Because of this legacy I cannot remove this class. This class inherits IDbContextFactory and it needs to retrieve a connection string, which now is hard coded. To make it more... dynamic, I want to use the Azure connection strings for this.
1 I added the connection string to the configuration of the app service
2 According to a lot of websites I can just add the following code to retrieve the connection string:
connectionString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
This does not work; it gives a "Object reference not set to an instance of an object." error.
Other say you need to add a prefix and the environment:
connectionString = Environment.GetEnvironmentVariable("SQLCONNSTR_DefaultConnection");
This does not work either, obviously. And yes, I selected sql server in the dropdown.
Other thing I tried, as someone suggested, is to add the connection string to the web.config. And again; this didn't work.
Good to know is that this is .NET 4.6.2, so all the beautiful solutions for .NET Core 1/2 aren't going to work.
First you have to include the same connection string in the web.config with empty connectionString value. Then you can overwrite from the application settings section.
`<connectionStrings>
<add name="DefaultConnection" connectionString="" />
<add name="CMSEntities" connectionString=""
providerName="System.Data.EntityClient" />
</connectionStrings>`
For entity framework specify providerName as "System.Data.EntityClient" and settings chose Custom instead of SqlServer

Entity Framework MigrateDatabaseToLatestVersion CREATE DATABASE permission denied in database 'master' error

I've been looking through questions on here but have yet to come across anything that deals with my problem, apologies if this is a duplicate and I've missed something.
I have an ASP.Net MVC project with Entity Framework Code First.
In my Dbcontext I have;
public Context() : base("DatabaseName")
{
System.Data.Entity.Database.SetInitializer(new MigrateDatabaseToLatestVersion<Context, Configuration>());
}
In my web config I have;
<connectionStrings>
<add name="DatabaseName" connectionString="connsection string is here"/>
</connectionStrings>
When my application is deployed, I get the error
'CREATE DATABASE permission denied in database 'master'.' as soon as
it tries to access the Context for the first time.
What I don't understand is how to stop it trying to create a database and just use the connection string that I have given it. The database already exists (It's on shared hosting so I don't have much control over it) and I know the connection string is correct as I have Hangfire installed in the same application, using the same connection string and it has successfully created the tables but for some reason EF doesn't create the tables in the database and instead tries to create one, which it cannot do.
Entity Framework is installed in the same project as the config file, in fact, it's a single project application.
I've tried creating another database and adding a second connection string in case Hangfire was preventing EF from using it but had the same issue. I've also tried putting the full connection string directly into :base("") on the context, but it has no effect.
try getting connectionString by name
public Context()
:base("name=DbConnection")
{
}
in Web.config file add
<connectionStrings>
<add name="DbConnection" connectionString="Data Source=serveraddress;Persist Security Info=False;User ID=usename;Password=pass;Initial Catalog=databasename" providerName="System.Data.SqlClient" />
</connectionStrings>

Interchange Connection string (Short cut to do something similar to Rename Refactoring)

I have two connection strings saved in Properties that I need interchangeability.
One is for a database that is used to test my application and the other is for the actuall database that the application will be used on.
My problem is that I have to use the connection string many times in different classes and as it stands now I am manually changing to the connection string by copy and paste.
Is it possible to do something similar as Rename Refactoring (C#) ,but not actually rename, but replace the connection string with the second one?
Ie, my first connection string is this,
using (SqlConnection connection = new SqlConnection(Properties.Settings.Default.ConnectionString_One))
Replace every connection string value into the second connection string,
using (SqlConnection connection = new SqlConnection(Properties.Settings.Default.ConnectionString_Two))
One is for a database that is used to test my application and the
other is for the actuall database that the application will be used
on.
If I understand correctly, you are trying to replace the connection string in the production build. Here's the step how to do it.
Save the connection string in config file
Sample code: (web.config OR app.config)
<connectionStrings>
<add name="ConnectionString" connectionString="{testing}" providerName="System.Data.SqlClient"/>
</connectionStrings>
Create a build transformation (by default, it would have debug build and release build
Replace the testing connection string with production connection string in release build
Sample code: (web.release.config OR app.release.config)
<connectionStrings>
<add xdt:Transform="Replace" xdt:Locator="Match(name)" name="ConnectionString" connectionString="{production}" providerName="System.Data.SqlClient"/>
</connectionStrings>
Hope it helps.
Read more at: https://msdn.microsoft.com/en-us/library/dd465318(v=vs.100).aspx

Regarding missing connection string in web.config

I am learning basics of MVC. And forgive me If I am not able to ask question properly because I am not aware of various technical terms. Anyways I am trying build one simple page where I will have two tables courses and Instructors. I am able to do most of the stuff and it seems to be working. Also I do have a solution given by my faculty of the same problem. When I am comparing my solution and faculty solution then in the web.config file of the actual solution given by my faculty I see something like
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-MvcCRUDwithSQL-20140217025002.mdf;Initial Catalog=aspnet-MvcCRUDwithSQL-20140217025002;Integrated Security=True"
providerName="System.Data.SqlClient" />
<add name="CourseContext" connectionString="Data Source=(localdb)\v11.0; Initial Catalog=CourseContext-20140217145250; Integrated Security=True; MultipleActiveResultSets=True; AttachDbFilename=|DataDirectory|CourseContext-20140217145250.mdf"
providerName="System.Data.SqlClient" />
</connectionStrings>
Where as in my solution that I just have one add name tag. I don't know why the another tag did not get created automatically. Or do I need to add that tag manually.
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-WebApplication9-20150313042831.mdf;Initial Catalog=aspnet-WebApplication9-20150313042831;Integrated Security=True" providerName="System.Data.SqlClient" />
Have I done something wrong that the connection string related to CourseContext did not get generated automatically. Or we need to add for CourseContext manually? Please help me. Since most of the files and its content are generated automatically I must have done something wrong that connection string pertaining to CourseContext did not get generated.
Use the steps below to generate the connection string via visual studio server explorer
Click on server explorer
Connect to database
Choose server name from dropdown
Choose your authentication type
Select your database from dropdown
Test connection
Copy the connection string from the properties and paste in your web.config
Also take a note of #Guffa answer, he's got a very good point
You don't need one connection for each table, you only need one connection for each database. A database can contain many tables (the project I'm working on right now has 9 tables, and that is a really small project).
The Visual Studio template starts out with a default connection string, but no database. It looks like it's that connection string that is still left in the solution.

How do I connect to an existing database in ASP.NET MVC?

I'm just starting to learn C# and ASP.NETMVC, but every example I've found puts the database in the App_Data folder. I don't want to do this.
I'd like to create a new version of Nerd Dinner and move the connection string to the web.config, but I can't find any examples on how to do it. My database is called NerdDinner and I'm using SQL Server Express.
What's the correct syntax to add the new connection string to my web config? Does this have any effect on creating LINQ to SQL classes?
I always go to http://www.connectionstrings.com/ when I forget how a connectionstring is written.
Standard security SQL Server 2008
Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;
Here is an article on MSDN talking about How to: Read Connection Strings from the Web.config.
You have a section almost at the top in your Web.config called connectionstrings, it could look something like this:
<connectionStrings>
<add
name="NorthwindConnectionString"
connectionString="Data Source=serverName;Initial
Catalog=Northwind;Persist Security Info=True;User
ID=userName;Password=password"
providerName="System.Data.SqlClient"
/>
</connectionStrings>
I would recommend however that you also look in to Entity Framework which is an abstraction between your code and the database, it makes it easier to work with "objects" in your database. You can find an introduction to ADO.NET Entity Framework here. But first of all you should focus on getting your connection up and running to your database using the information at the top.
An additional way to have your context 'point' to the connextionsStrings line in the web.config file is to try this constructor.
public class MainDB : DbContext
{
public MainDB() : base ("name=DefaultConnection")
{
}
public DbSet<User> Users { get; set;}
}
Then change the name to DefaultConnection in the web.config file.

Categories