SHORT VERSION: Is it possible and how to define a variable in a web.config file that I can use within itself.
I am new to a company and also a beginner developer in C# MVC Web applications. I have been tasked to maintain and test a web application that has multiple connections strings in a single web.config file. These connection strings, however, have the same values in it like:
<connectionStrings>
<add name="DefaultConnection" connectionString="provider=System.Data.SqlClient;provider connection string="data source=SUPERCOMPUTER\SQLEXPRESS2012;initial catalog=HumanResourceDB;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
<add name="DefaultConnection3" connectionString="Data Source=SUPERCOMPUTER\SQLEXPRESS2012;Initial Catalog=HumanResourceDB;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
As you can see, the difference with these two is just the Name of the connection. Since Im a beginner I don't exactly know why this application has to use 2 same connection strings with different names. I was told that one is being used by Database First entity framework and the other is being used by ASP.NET Identity Code First and I do not know right now what those are.
The problem: I am CONSTANTLY changing connection strings value to test with different machines/environment/database etc and the need to modify 2 connection strings is really slowing me down.
The question: Is it possible to use variables that I can just declare at the top of the web config file and use it in the connection strings so that I can just modify the variable values. Something like this:
var Server = SUPERCOMPUTER\SQLEXPRESS2012
var IntegratedSecurity = true
var database = HumanResourceDB
var user = databaseusername
var password = databasepassword
<connectionStrings>
<add name="DefaultConnection" connectionString="... data source=**Server**;initial catalog=**database**;integrated security=**IntegratedSecurity **;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
<add name="DefaultConnection3" connectionString="Data Source=**Server**;Initial Catalog=**database**;Integrated Security=**IntegratedSecurity**" providerName="System.Data.SqlClient" />
</connectionStrings>
Additional Question: Is it really impossible to use one connection string if the mvc application relies on both Database First Entity Framework and Code First .NET Identity?
All EF project have a dbContext File..so you can use multiple EF projects(Code First, DB first) in just one solution.
Yes its clearly possible ...in code first your db context can get the name of each ConnectionString you want!.. like this:
public class AppContext : DbContext
{
public AppContext() : base("ConString Name")
{
}
}
so you can change the connection string name to another one..like DefaultConnectionString1 to DefaultConnectionString12 or 1000 ...
and you can have multiple db context to work on multiple databases to...
in Code first from database is like that to ...so in each part of project you can make instanse of which dbcontext you like. and do CRUD operation on that..
Related
So I have Solution with two projects. The first projects should act as a Data Access Layer so there in the app.config file I have this:
<connectionStrings>
<add name="BloggingContextCF"
connectionString="provider=System.Data.SqlClient;
provider connection string="
data source=*****\SQLEXPRESS;
initial catalog=CodeFirst.Blogging;
integrated security=True;
MultipleActiveResultSets=True;
App=EntityFramework""
providerName="System.Data.EntityClient" />
The second Project is a ASP.NET Web Forms project, where I removed the default connection string pointing to the (local) instance leaveing only one connection string, the one from the first Data Access Layer project. Which actually works and the database is created on my SQL 2008 R2 server, but instead of the desired (and expected) database name - CodeFirst.Blogging the name is DataAccessLayer.BloggingContextCF where DataAccessLayer is the name of the project and BloggingContextCF is the class extending DbContext.
What I need to change in my connection string so I can get the desired name?
Try
public BloggingContextCF ():base("CodeFirst.Blogging") {}
make the connections string like
Point it to sql client
providerName="System.Data.EntityClient"
to
providerName="System.Data.SqlClient"
For full connection string do it like
<add name="BloggingContextCF" connectionString="Server=YOUR_SERVER;Database=DATABASE_NAME;User ID=USER_ID;Password=PASSWORD;Trusted_Connection=False;Encrypt=True;Connection Timeout=30;" providerName="System.Data.SqlClient" />
For more connectionstring example follow the link
and don't forget to modify your dbcontext
public class YourContext : DbContext
{
public UsersContext()
: base("BloggingContextCF"){ }
}
ask your advices about this:
I am trying to create db compact edition,
first time it was successfully with default dbName (ProjectName.dbContextName).
But i decided to define my own name, and added in app.config in connectionString sections my connection string. After db was not created.
From here MSDN Use code first with connection by convention i have done similar connection string:
<connectionStrings>
<add name="TestContext"
providerName="System.Data.SqlServerCe.4.0"
connectionString="Data Source=TestDb.sdf;"/>
</connectionStrings>
(section name is equal to my dbcontext's name class.)
Just to be sure before dbContext will be created:
Database.SetInitializer(new DropCreateDatabaseAlways<TestContext>());
Db still is not created. What am i doing wrong? Thanks in advance.
VahidN, i tried to add call of base class constructor, but doesn't work. Don't understand. It should be very easy. And as were aforementionted in ref above, if name of connection string in config section and name dbContext class are equal - object finds its connection string without problems.
Well, debugger says that conString is defined correctly (equal to string in config section), but actually db is not created - i can't find it nor in appfolder nor in sql server folders.
You need to include the full namespace in the name of the connection-string. See here.
Something like this
<connectionStrings>
<add name="YourNameSpace.TestContext"
providerName="System.Data.SqlServerCe.4.0"
connectionString="Data Source=TestDb.sdf;"/>
</connectionStrings>
Oh, sorry me for giving insufficient information, db was not created cause entities in dbContext was defined as List, not dbSet. inadvertency (
An application of mine uses LINQ-to-SQL extensively, and it is now a requirement of the application to be able to switch which database it is looking at at runtime - so essentially I would like to be able to choose the connection string of my data context when I declare it.
Is there an easy way of doing this?
Just call :
DataContext context = new DataContext ("cxstring");
You could use an App.config to store your Connection Strings then use them to populate a drop down box or something. Then use the selected Connection string in the constructor of your LINQ2SQL data context.
App Config:
<configuration>
<connectionStrings>
<add key="ConString1" connectionString="ConnectionStringGoesHere"/>
<add key="ConString2" connectionString="ConnectionStringGoesHere"/>
</connectionStrings>
Use the ConfigurationManager class to access your connection strings.
string conString = ConfigurationManager.ConnectionStrings["ConString1"].ConnectionString;
You can also enumerate over them or set them as datasource to populate a drop down box.
Then simply pass the selected string in as the first parameter in your LINQ2SQL datacontext constructor.
MyModelDataContext context = new MyModelDataContext(selectedConString);
If you mean by switching which database your application is looking at ,Test database and production database , simply you can make two connection string in your web.config file with the same key but has different connection string and comment one of them according to the desired database
<add name="MyConnectioString" connectionString="Data Source=myServer;Initial Catalog=ProductionDB;" providerName="System.Data.SqlClient" />
<!--<add name="MyConnectioString" connectionString="Data Source=myServer;Initial Catalog=TestDB;" providerName="System.Data.SqlClient" />-->
by comment and uncomment you can switch between the 2 databases in run time.
to choose the connection string of your context provide it with its constructor
DataContext Productioncontext = new DataContext ("MyConnectioString");
What does this error mean?
Format of the initialization string does not conform to specification starting at index 0.
and also getting this error:
The specified named connection is either not found in the configuration, not intended to be used with the EntityClient provider, or not valid.
I'm trying to use my EF model context in another project in Visual Studio. Having real trouble just getting my EF application off the ground.
I instantiate the model context like so:
ctx = new VisitoriDataModel("VisitoriDataModel");
I have the connection string copied from the data layer project into all projects including the web.config and still no luck.
Also tried the following:
//model = new VisitoriDataModel(new EntityConnection("Name=VisitoriDataModel"));
//model = new VisitoriDataModel("Name=VisitoriDataModel");
//model = new VisitoriDataModel("VisitoriDataModel");
//model = new VisitoriDataModel();
ConnectionString is like so:
metadata=res://*/Context.VisitoriDataModel.csdl|res://*/Context.VisitoriDataModel.ssdl|res://*/Context.VisitoriDataModel.msl;provider=System.Data.SqlClient;provider connection string="data source=.\SQLEXPRESS;initial catalog=visitori;integrated security=True;multipleactiveresultsets=True;App=EntityFramework"
The connection string needs to go in the project that is being executed. If this is a website, that would be the web.config. Make sure it's correctly nested, and not inside another node like <system.web>, you should have:
<configuration>
...
<connectionStrings>
<add name="VisitoriDataModel" connectionString="metadata=res://*/Context.VisitoriDataModel.csdl|res://*/Context.VisitoriDataModel.ssdl|res://*/Context.VisitoriDataModel.msl;provider=System.Data.SqlClient;provider connection string="data source=.\SQLEXPRESS;initial catalog=visitori;integrated security=True;multipleactiveresultsets=True;App=EntityFramework""
providerName="System.Data.EntityClient" />
</connectionStrings>
...
</configuration>
Also note that the "'s around the provider connection string inside the entity connection string need to be escaped as "
How to connect to different databases for a .NET MVC web application written in C#?
Here the stucture of the database table remains the same. All that changes is the database name. So how to I manually connect to a database or use modify the connection string?
The trick is to use the same code. Depending on the URL I want the data to be displayed from different database. So the Views and Controller (pretty much) has single code w.r.t. the Model.
-Datte
Here's a very simple way to do what I think you're asking. In your web.config file, you could define your two connection strings:
<connectionStrings>
<add name="DevelopmentDB" providerName="System.Data.SqlClient"
connectionString="Data Source=sql-dev.example.com;Initial Catalog=MyDB;User Id=MyUser;Password=MyPassword" />
<add name="ProductionDB" providerName="System.Data.SqlClient"
connectionString="Data Source=sql-prod.example.com;Initial Catalog=MyDB;User Id=MyUser;Password=MyPassword" />
</connectionStrings>
Then, in your (base) controller, you could create a method that returns the appropriate connection string based upon the request, such as:
internal string ConnectionString
{
get
{
return getConnectionStringByServerName(this.HttpContext.Request.ServerVariables["SERVER_NAME"]);
}
}
internal string getConnectionStringByServerName(string serverName)
{
if (serverName.Equals("localhost"))
{
return WebConfigurationManager.ConnectionStrings["DevelopmentDB"].ConnectionString;
}
else
{
return WebConfigurationManager.ConnectionStrings["ProductionDB"].ConnectionString;
}
}
You could of course change the selection criteria for whatever makes the most sense.
Good luck!