I am working on a MVC 4 web site. It should allow the user to select which database to be connected with depending on user selection from the View. All the databases have the same table structure and schema etc.
I have a database ConnectionString defined in the Web.config file that allows for connection to the first database.
<connectionStrings>
<add name="DBConnectionString" connectionString="Data Source=DATABSE_SERVER;Initial Catalog=DATABASE_NAME;Persist Security Info=True;User ID=USERNAME;Password=PASSWORD" providerName="System.Data.SqlClient" />
</connectionStrings>
I also used Linq DataContext to initialize connection to the database. Table mappings were all automatically generated by Linq to SQL in MVC 4.
public NEMP_DataDataContext() :
base(global::System.Configuration.ConfigurationManager.ConnectionStrings["DBConnectionString"].ConnectionString, mappingSource)
{
OnCreated();
}
What is the best way to achieve this?
In LINQ to SQL, you just create the Context with the connection string:
DataContext myContext = new DataContext(customConnectionString);
You don't need to worry about closing them or anything. SQL Server is handling all that for you. So you simply adjust the connection string slightly (Database Name) and create a new context based on whatever variable in every page you need to use the Context.
You can use the ChangeDatabase method of SqlConnection
See MSDN.
First of all, you should have a storage to get all of the database connections.
Maybe the storage is a xml file or a simple database.
But you need to implement how to get the connection strings.
If you have used EntityFramework for your dataconext in your applicaiton.
You could have a constructor like the folowing code:
public ApplicationDbContext(string nameOfConnection)
: base(nameOfConnection)
{
this.Configuration.ProxyCreationEnabled = true;
this.Configuration.LazyLoadingEnabled = true;
}
Please invoke the 1 and get the nameOfConneciton, then invoke 2 to initialize the DbContext.
I'm not sure if I understand your question fully. But I assume you ask us that you want to let the user select the database they want to connect to. Then set the connection string.
Here's my solution, for example if you have 5 database to let user to select. You write those 5 connection string into web.config. Then make something like a drop down list or radio button that let's user to select database. And then make a if statement. For example if the first radio button is selected then
String connection string=connection.string["the name of connection string in web.confug"];
I hope this help you
Related
So, I'm writing a program that imports excel files to a database, finds matches, non matches, shows the tables, etc.
In the beginning I added manually just my database connection string, but I have to make my program let the connection string change.
In case none is inserted, it will use the last one inserted.
Behind code:
protected void BtnFazerTudo_Click(object sender, EventArgs e)
{
var connectionString = ConfigurationManager.ConnectionStrings["Db"].ConnectionString;
connectionString = connectionString.Replace("{username}", TxtUtilizador.Text);
connectionString = connectionString.Replace("{pwd}",TxtPalavraPasse.Text);
connectionString = connectionString.Replace("{DataSource}", TxtHost.Text);
connectionString = connectionString.Replace("{Initial}", TxtBaseDeDados.Text);
Debug.Write(con);
}
Web Config:
<add name="Db" connectionString="Data Source ={DataSource} ;Initial Catalog=
{Initial};Persist Security
Info=True;User ID={username};Password={pwd}"/>
I already tried the String builder. I was able to output it in the debug window but I have no idea in how I transfer that connection made by string builder to other web forms.
The connection string you're creating needs to be stored somewhere so as all pages of your web application can access it. While there are some choices that let you pass data among pages none of them suits you mainly because (a) the connection string contains security sensitive information such as the password!!! and (b) they do not offer the level of persistence required by your scenario (unless you want the user to fill the textboxes every time he connects to your application).
Having said that, one viable option is to store the connection string in a database and retrieve it every time you need it. You can either store it as a whole string or each user data separately (i.e catalog, user id, password etc). In the latter case, you'd have to re-create the connection string every time you need it.
How you create the connection string has nothing to do with your original question. It is just about string concatenation in C# for which you can use the + or += operators, string interpolation or the String.Format, String.Concat, String.Join or StringBuilder.Append methods.
I am trying to connect to a SQL Server database in my website. I have created a database from Add -> Add New Item -> SQL Server database. The name of my database file is database.mdf.
I have created a ConnectionString:
<connectionStrings>
<add name="Khulna_website"
connectionString= "Server=(localDB)\\v11.0;Integrated Security=SSPI;Database=Database.mdf;"
providerName="System.Data.SqlClient" />
</connectionStrings>
My first question is, when I open a database that way, is it necessary to add a connection string? Asking that because I can already see a green connection line on the side of the database.
Then, how do I connect it on my C# code?
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
conn.Open();
The question is, what do I add on ["RegistrationConnectionString"] part? Should I give the name of my ConnectionString? Am I missing any point here? I am completely new here. Any help would be highly appreciated.
Yes, in order to connect to a database - you do need some form of a connection string - one way or another. It's typically considered a best practice to put those connection strings into a config file, so you can modify it without changing your code.
To retrieve the actual connection string from the config, you need to use the name=.... to you gave it in the config file:
<add name="Khulna_website"
*************** this is the **name** of your connection string
Retrieve it like this:
string conStr = ConfigurationManager.ConnectionStrings["Khulna_website"].ConnectionString;
************** same name again
and then use it to create your connection object to the database:
SqlConnection conn = new SqlConnection(conStr);
Put the name of the connection string which is Khulna_website instead of RegistrationConnectionString
I am developing an WPF application with EF 6 database first approach, I am have 1 project in my solutions, if i run my project this error always appear.
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. If you are creating your own DbConnection, then make sure that it is an EntityConnection and not some other type of DbConnection, and that you pass it to one of the base DbContext constructors that take a DbConnection. To learn more about Code First, Database First, and Model First see the Entity Framework documentation here: http://go.microsoft.com/fwlink/?LinkId=394715
My mistake was using standard connection string in constructor
(Server = test\test; Database = DB; User Id = test_user;Password = test),
but Entity Framework needs different format
(metadata=res://*/DBModel.csdl|res://*/DBModel.ssdl|res://*/DBModel.msl;provider=System.Data.SqlClient;provider connection string="data source=test\test;initial catalog=DB;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework""" providerName = ""System.Data.EntityClient)
Edit: Changed code to be formatted as code so it's easier to read.
EF makes assumptions based on the presence or absence of a metadata section in the connection string. If you receive this error you can add the metadata section to the connection string in your config file.
E.g. if your connection string looks like this:
<add name="MyModel" connectionString="data source=SERVER\INSTANCE;initial catalog=MyModel;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" />
Prepend metadata=res://*/MyModel.csdl|res://*/MyModel.ssdl|res://*/MyModel.msl; so that it looks like this:
<add name="MyModel" connectionString="metadata=res://*/MyModel.csdl|res://*/MyModel.ssdl|res://*/MyModel.msl;data source=SERVER\INSTANCE;initial catalog=MyModel;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" />
One thing you can do is... (if is Database first)
Open the .edmx[Diagram] -> right click -> "Update Model from database"
And see if the will appear the "Add", "Refresh" and "Delete" tabs.
If doesn't... probably your connection is broken and the dialog for VS creates a new connection string will appear instead. =)
You shouldnt use generated connection string, now you have all metadata files included in your solution. Instead try use in connection string section of app.config:
"data source=localhost\sqlexpress; initial catalog=sample; integrated security=True;MultipleActiveResultSets=True;"
None of the above solutions worked for me. But I did find the SqlConnectionBuilder class here which did work: https://learn.microsoft.com/en-us/dotnet/api/system.data.entityclient.entityconnectionstringbuilder?view=netframework-4.8
Its the same as specifying the string as some of the other suggestions here but it builds the string for you.
// Specify the provider name, server and database.
string providerName = "System.Data.SqlClient";
string serverName = ".";
string databaseName = "AdventureWorks";
// Initialize the connection string builder for the
// underlying provider.
SqlConnectionStringBuilder sqlBuilder =
new SqlConnectionStringBuilder();
// Set the properties for the data source.
sqlBuilder.DataSource = serverName;
sqlBuilder.InitialCatalog = databaseName;
sqlBuilder.IntegratedSecurity = true;
// Build the SqlConnection connection string.
string providerString = sqlBuilder.ToString();
// Initialize the EntityConnectionStringBuilder.
EntityConnectionStringBuilder entityBuilder =
new EntityConnectionStringBuilder();
//Set the provider name.
entityBuilder.Provider = providerName;
// Set the provider-specific connection string.
entityBuilder.ProviderConnectionString = providerString;
// Set the Metadata location.
entityBuilder.Metadata = #"res://*/AdventureWorksModel.csdl|
res://*/AdventureWorksModel.ssdl|
res://*/AdventureWorksModel.msl";
Console.WriteLine(entityBuilder.ToString());
using (EntityConnection conn =
new EntityConnection(entityBuilder.ToString()))
{
conn.Open();
Console.WriteLine("Just testing the connection.");
conn.Close();
}
I also faced this exact same message, but workig with a web MVC project. This message is fired when I try to auto generate the Controller from the imported model. It seems that it is not working because "that was generated from an EDMX file".
The good news is that it works if I generate the model based in the "Code First" instead of "EF Designer". The bad news is that I can't use the EF Designer if I want that the automatically controller generation works. Does not matter which from those two ways you generates your model. Once the model is generated, you use it in the same way.
Tries to remove all your emdx objects from your project and recreate the model based in the Code First instead of EF Designer. Worked for me!
Very much late but still helpful. I got stuck in a similar problem. Posted a question about on SO and was able to find a solution. You can refer to Connection String errors in C# Web Api.
My situation was I had two connection strings in web.config (you'll get to know why when go to the link). Commenting one string was raising the error you got while commenting the other one was raising error as below:
An error occurred when trying to create a controller of type 'AccountController'. Make sure that the controller has a parameterless public constructor.
what i did was: I named my first connection string as DefaultConnection and in ApplicationDbContext class constructor I gave this DefaultConnection. Now my AccountController uses this connection string and all other controllers use second connection string.
This solved my problem.
I have two projects:
One is for the generated EDMX file and all related models.
The other one is the ASP.NET MVC Web.
I encountered this issue since the connection string that I am using on the ASP.NET MVC Web project is the normal string that I use using ADO.NET connection. So what I did is the following:
Open the app.config on your EDMX project files.
Copy its connection string.
Paste it on the WEB project since this will be used when you start
the application.
In my data import application I want to allow the user to import data from as much different data sources as possible.
So what is the best way and what are the classes needed to be able to connect to different data sources and then get data from them via SQL queries?
E.g.
// 1. A class I need to allow the user to select the needed data source
ConnectionDialog dlg = new ConnectionDialog();
dlg.ShowDialog();
// 2. A class I need to access the data source using the connection string built above
DataConnection con = new DataConnection(dlg.builtConnectionString);
con.doStuff("SELECT * FROM test");
Currently I'm using the Microsoft connection dialog (http://archive.msdn.microsoft.com/Connection) for the first part. But I can't figure out how to use the connection strings returned by it. An OdbcConnection won't accept it (only tested with an Micrsosoft SQL connection string generated by the dialog). Is it even possible to achieve the above or will I be forced to use different classes for the second part?
Edit: I also want the user to be able to install his own drivers for data sources. I just don't know if ODBC or OleDB or anything else is the way to go and if/how I can use the connection dialog with this.
Use wrapping to list of DB sources. Add a connection strings to web.config for each type of DB connection (MSSQL , MYSQL and Oracle) with {{name}} string and then replace this string with the catalog selected by the user.
<connectionStrings>
<add name="mssql" connectionString="Data Source=.;Initial Catalog={{name}};Integrated Security=True" />
<add name="mysql" connectionString="server=localhost;user id=root; password=PASS;database={{name}};pooling=false" />
<add name="oracle" providerName="Oracle.DataAccess.Client" connectionString="Data Source={{name}};User Id=root;Password=PASS;" />
</connectionStrings>
Now use SqlConnection and MySqlConnection and OracleConnection classes . (You will need mysqlconnector and oracleconnector for these classes).
I have two connection strings (both in Web.Config: CS_Local and CS_Production) for my DBML (Linq to SQL).
In my Global.Asax/Application_Start I run some production preparation methods if the request is non-local (!HttpContext.Current.Request.IsLocal). Within that part, I'd also like to change the current connection string used by my DBML from the standard CS_Local to CS_Production.
How would I do that? Some help please..
You can define the dbml context on the fly with:
string connectionString = HttpContext.Current.Request.IsLocal ?
ConfigurationManager.ConnectionStrings["CS_Local"].ConnectionString :
ConfigurationManager.ConnectionStrings["CS_Production"].ConnectionString;
yourDataContext = new YourApplicationDataContext(connectionString);