Changing LINQ-to-SQL connection string at runtime - c#

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");

Related

MVC WebConfig Variable for Multiple Connection Strings

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..

DataContext does not contain a constructor with 0 parameters

I am learning with this so bear with me...I am trying to create the DB object to access the table.
AppDatabaseDataContext appDb = new AppDatabaseDataContext();
This gives me an error, so I create the constructor...
public AppDatabaseDataContext()
{
}
Now this tells me that System.Data.Linq.DataContext does not contain a constructor that takes 0 parameters. Why?
Thanks!
You need to specify a connection string. If you know it's always going to be the same (for example, localhost) you can just hard-code it in your parameterless constructor:
public AppDatabaseDataContext()
: this(#"Data Source=localhost;Initial Catalog=Foo;Integrated Security=True")
{
}
Notice how we chain the constructor to call the version that consumes a connection string. This way, you can instantiate the data context using the parameterless constructor, and it will use this default connection string.
Sometimes LINQ2SQL might become messy on properties window and the connection string might disapear.
If you can, restart all over, remove de Dbml and but DONĀ“T FORGET to delete from the web.config the connection string. Add a new Linq2SQL to your project and let the LINQ2SQL to create the connection string for U in the web.config.
It's strange. Every time I've used a "LINQ to SQL" DataContext in the past, it's always created a 0-argument constructor for me.
But today, I was finding that sometimes, in the Designer, it wouldn't let me select a particular (known) connection string in the Properties window... and when this happened, it refused to create this 0-argument constructor.
The solution was to manually add it myself.
My web.config contained a connection string called MikesConnectionString :
<configuration>
<connectionStrings>
<add name="MikesConnectionString" connectionString="Data Source=localhost;Initial Catalog=MikesDatabase;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
... so in my survey.designer.cs file, I added this:
public SurveyDataContext() :
base(global::System.Configuration.ConfigurationManager.ConnectionStrings["MikesConnectionString"].ConnectionString, mappingSource)
{
OnCreated();
}
Job done.
But odd. Very odd.
Just Change your connection string just like
<connectionStrings>
<add name="DBLabConnectionString"
connectionString="Data Source=.\SQLExpress;Initial Catalog=DatabaseName;
Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>

Shared Connection Strings in Entity Framework

I want to create a single connectionString in my Web.config and then re-use it in the "provider connection string" attribute of all Modules declarations.
example :
Declare a connection string this way:
<add name="MyConnectionString" connectionString="Data Source=.;Initial
Catalog=MyDB;User ID=username;Password=pwd;" />
and then share this connection between modules:
<add name="Module1Context" connectionString="metadata=res//*/Module1.csdl| ... |
...;provider=System.Data.SqlClient;provider connection string=MyConnectionString"
providerName="System.Data.EntityClient" />
Is this possible?
It's not directly possible the way you have it described above.
The solution for this is almost certainly going to be FAR more work than just copying your connection strings, commenting or uncommenting entries as you go.
Be sure you are using Configuration Transformation files to manage this.
If you really must do this, then you will need to build the connection strings yourself, using the EntityConnectionStringBuilder class, pulling the provider connection string from your MyConnectionString value. Set the EntityConnection property in your context object when you instantiate it; see http://msdn.microsoft.com/en-us/library/bb896325.aspx for details.
You can manage your connection string in runtime using ConfigurationManager.ConnectionStrings
http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.connectionstrings.aspx

specified named connection is either not found or Format of the initialization string does not conform to specification starting at index 0.

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 "

Entity Framework Connection String Trouble

I am making a little library(DLL) to manage users and their roles/privileges. The plan is to be able to add this dll to an MVC project and be able to manipulate users/roles/etc. All the data resides in a SQL db.
I am using entity framework for data access.
So when I initialize a new RoleManager(this is the name of the main class in the lib I'm making) I supply it with a connectionString like so:
RoleManager roleManager = new RoleManager(string connectionString);
Then inside the constructor I do this:
db = new RoleManagerEntities(connectionString); //This is the EntityFramework
And I am trying to supply this connection string (among many others)
"metadata=res://*/RoleManager.csdl|res://*/RoleManager.ssdl|res://*/RoleManager.msl;provider=System.Data.SqlClient;provider connection string='Data Source=localhost;Initial Catalog=Login;Integrated Security=True;Connection Timeout=60; multipleactiveresultsets=true'"
And I get the following error:
The specified named connection is either not found in the configuration, not intended to be used with the EntityClient provider, or not valid.
This question is a result of having trying to instantiate the EF from my new project without supplying a connection string and without having anything inside my app config for it to default to. Too bad I can't delete it now.
Just copy the connection string information from your DLL config file to your executable config file.
Basically you are trying to instantiate an ObjectContext via this ObjectContext Constructor (String) without passing the string parameter in its expected format and that's the problem.
Here is what you need to do:
1. First create an entry in your in your "test project" app.config because that is the place that the CLR is looking at to find the connection string at runtime.
<configuration>
<connectionStrings>
<add name="RoleManagerEntities" connectionString="metadata=res:///RoleManager.csdl|res:///RoleManager.ssdl|res://*/RoleManager.msl;provider=System.Data.SqlClient;provider connection string='Data Source=localhost;Initial Catalog=Login;Integrated Security=True;Connection Timeout=60; multipleactiveresultsets=true'" />
</connectionStrings>
</configuration>
2. Now change the code to pass the connection string name instead of the actual connection string:
db = new RoleManagerEntities("name=RoleManagerEntities");
The constructor might be looking for a connection string in the connectionStrings setting of your web.config with the name that you pass it as the parameter.
So if you call:
db = new RoleManagerEntities("Foobar");
It is looking for:
I'm not positive that this is the solution but that's what the error message seems to indicate.
I am not an expert on EF, but I don't think that connection string is valid. Try:
metadata=res://*;provider=System.Data.SqlClient;provider connection string='Data Source=localhost;Initial Catalog=Login;Integrated Security=True;Connection Timeout=60; multipleactiveresultsets=true'

Categories