I saw a lot of similar questions but the answer is the same.
public class myContext(string connectionName) : base(connectionName)
{
}
The problem is all of their answers specify a connection NAME derived from their .config like:
<connectionStrings>
<add name="connectionName"
connectionString="data source=server\database;initial catalog=catalog;persist security info=True;user id=user;password=password;MultipleActiveResultSets=True;App=EntityFramework"
providerName="System.Data.SqlClient" />
</connectionStrings>
What if I want to pass something like this
"Server=127.0.0.1;Database=sampleDB;User Id=foo; Password=bar"
or something like
"Server=127.0.0.1;Port=440;Database=mysqlDB;Uid=root; Pwd=root123;"
The c'tor of DbContext takes a string that is named nameOrConnectionString.
From the documentation:
Parameters:
nameOrConnectionString:
Either the database name or a connection string.
So you can pass both, a name to a connection string, or the direct connection string.
Pass a name:
To pass a name to DbContext (e.g. in your web.config), write something like:
new myContext("name=connectionName")
Pass a connection string:
To pass a literal connection string, write something like:
new myContext("Server=127.0.0.1;Database=sampleDB;User Id=foo; Password=bar")
Related
I have multiple projects being hosted in IIS. These all share a database, which is called using EF6. I want to be able to use a shared connection string config file which I can reference from each of the other projects' web.config. This way, I'm able to manage any chances to the connection string from a single location. From what I've found online, I'm trying to accomplish this through a Virtual Directory and the configSource attribute for the connectionString.
IIS structure
-VirtualDirectory (mapped to /DbConfigFile)
-WebApp 1
-WebApp 2
-WebApp 3
WebApps' Web.config connectionString sections
<connectionStrings configSource="/DbConfigFile/testDB.config"></connectionStrings>
The external config file (testDB.config) containing the connectionString needed by all applications.
<connectionStrings>
<add name="TestDBEntities" connectionString="metadata=res://*/TestDB.csdl|res://*/TestDB.ssdl|res://*/TestDB.msl;provider=System.Data.SqlClient;provider connection string="data source=TestDB;initial catalog=VBODashboard;persist security info=True;user id=Test;password=Test;MultipleActiveResultSets=True;App=EntityFramework""
providerName="System.Data.EntityClient" />
</connectionStrings>
I've tried various paths in the configSource attribute with no luck (~/DbConfigFile/testDB.config, testDB.config). How would I access this file? Or is there a better way to accomplish this?
I ended up going with one of mason's suggestions and creating a custom configuration file. That let me to research finding out that a connection string can be specified through code when initializing the context. I then navigated through the XML file through code and extracted the connection string value. :
public partial class TestDBEntities : DbContext
{
public TestDBEntities()
: base(<calling code to get connection string> , true)
{
}
...
}
I am using an Oracle DB with EF 6 code first.
And did custom encryption on connection string.
Connection string stores in separate config file "connstring.config": There is a clear connection string without encryption
<?xml version="1.0" encoding="utf-8" ?>
<connectionStrings>
<add name="MyConnString" connectionString="Data Source=MySource;User ID=UserID;Password=Password;PERSIST SECURITY INFO=True;"
providerName="Oracle.ManagedDataAccess.Client" />
</connectionStrings>
Data sources in web.config file.
MyDbcontext:
public static string GetConnectionString()
{
string encodedConnStr = ConfigurationManager.ConnectionStrings["MyConnString"].ConnectionString.ToString();
string result = Crypto.Decrypt(encodedConnStr);
return result;
}
public MyDbContext() : base(GetConnectionString()){}
And when I run application I am getting Server Error : Unable to complete operation. The supplied SqlConnection does not specify an initial catalog or AttachDBFileName.
How can I solve this?
Because you are passing the connection string directly to the DbContext constructor you need to provide it with a database provider otherwise it does not know what database type it is creating connections for. The easiest thing to do is to alter the connection string, you can do this post encryption in your static method or in your encrypted connection string. Based on your connection above I believe oracle.manageddataaccess.client is the correct provider but test it and see.
Provider=oracle.manageddataaccess.client;Data Source=MySource;User ID=UserID;Password=Password;PERSIST SECURITY INFO=True
You can also try thing according to this other answer I found on SO: How to set manually an Oracle Connection String in a DbContext
class MyDbContext: DbContext
{
public MyDbContext() : base(new OracleConnection(GetConnectionString()){}
...
}
If you are still experiencing problems update your question with just the relevant parts: that you cannot instantiate a DbContext instance when you manually provide a connection string. As it is written now it is very easy to make the assumption that your issue was with the encryption/decryption but these are irrelevant to the actual problem.
It was solved by setting defaultConnectionFactory to
Oracle.ManagedDataAccess.EntityFramework.OracleConnectionFactory, Oracle.ManagedDataAccess.EntityFramework
I have a connection string in my web.config file like this
<add name="ModelDbContext"
connectionString="metadata=res://*/Models.DizlyModel.csdl|res://*/Models.DizlyModel.ssdl|res://*/Models.DizlyModel.msl;provider=System.Data.SqlClient;provider connection string="data source={Server},1433;initial catalog=Dizlybeta;user id={id};Password={Password};MultipleActiveResultSets=True;App=EntityFramework""
providerName="System.Data.EntityClient" />
but then I go to my hosted azure website and place this as connection
And then I replace the hidden security with
metadata=res://*/Models.DizlyModel.csdl|res://*/Models.DizlyModel.ssdl|res://*/Models.DizlyModel.msl;provider=System.Data.SqlClient;provider connection string="data source={Server},1433;initial catalog=Dizlybeta;user id={id};Password={Password};MultipleActiveResultSets=True;App=EntityFramework"
but it still doesn't work, can anyone help me with how to place the right connection string in the website configuration?
Something to try:
Use a SqlClient connection string instead of an EntityClient connection string.
In that case, you'll probably need to pass the name of the connection string to the DbConext constructor, which you can do in one place like:
public MyDbContext : base("sqlClientConnectionStringName")
{
}
You might also need to ensure a SqlClient provider exists. Check the docs for more.
I have modified the web.config connection string. However, during debug, I still see the old connection string.
So, I have commented (and deleted) out the old connection string but, and added a new connection resource via server explorer. On testing the connection via wizard on the left panel in server explorer- it says connected.
After following this wizard, when I visit the web.config I dont see the new connection string.
Question: I suspect, I am not following the steps to add a connection string -
how can I add or update the connection string from the designer (in the designer properties panel, edit is greyed out, output type is build to assembly, and right clicking only gives me options to add entities etc, deleting the string and running the app, doesn't prompt for connection string wizard)
Below is the string -
<connectionStrings><add name="MaintRecordsDB_v1" connectionString="metadata=res://*/Models.DB.Model.csdl|res://*/Models.DB.Model.ssdl|res://*/Models.DB.Model.msl;provider=System.Data.SqlClient;provider connection string="data source=xxx.sample.net;initial catalog=MainDB;user id=maintRoot;password=hidden;multipleactiveresultsets=True;application name=EntityFramework"" providerName="System.Data.EntityClient" /><add name="MainDBentities" connectionString="metadata=res://*/Models.DB.Model.csdl|res://*/Models.DB.Model.ssdl|res://*/Models.DB.Model.msl;provider=System.Data.SqlClient;provider connection string="data source=windflower.arvixe.com;initial catalog=MX_Dashboard;user id=maintRoot;password=hidden;multipleactiveresultsets=True;application name=EntityFramework"" providerName="System.Data.EntityClient" /></connectionStrings>
Edit Question 2: How can I add another EF connection string for e.g. MaintDB2 using designer, and where do I update to this manually.
Without knowing what your context class looks like, say your DbContext class, if it was generated and assuming it's partial, you could try to add another partial class part to it with a constructor that takes a named connection string as an argument.
First add a named connection to your app.config/web.config:
<connectionStrings>
...
<add name="MyOtherConnection" connectionString="metadata=res://*/blahblahblah;provider=System.Data.SqlClient;provider connection string="Data Source=ABunchOfOtherStuff;"
providerName="System.Data.EntityClient" />
</connectionStrings>
Then add a matching partial class in another (non-generated) file with a constructor to take a connection string name:
// the class name must match the name of your existing context
public partial class MyContext : DbContext
{
public MyContext(string connectionStringName) : base("name=" + connectionStringName)
{
}
}
Then use your context by passing in the name of the connection string, demonstrated by some useless code:
// ...
using (var context = new MyContext("MyOtherConnection"))
{
var id = 1;
var collection = context.MyEntities.Where(a => a.ID == id).ToList();
}
In MVC several things are based on Convention. It prefers convention over configuration. By convention there should be a link between the two things. The class name of DbContext match the connection string for it to work correctly by convention
The class inheriting from DbContext say
public class DbPersonContext : DbContext
{ ... }
must have a connection string of the name Person
updated question
How do I specify the data source to my local MSSQL server?
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=(localhost)\SQLEXPRESS;Initial Catalog=bladb;Integrated Security=true" providerName="System.Data.SqlClient" />
</connectionStrings>
I keep getting a "data source not found" exception no matter what I try.
Yep. Your application needs to know the location of the database, the username, and password to authenticate with.
You call this a magic string but I don't know what other magic method you are thinking of where your application could automatically know the IP Address of your database, the Username, and the Password.
Most of the time when you setup your database they create this connection string for you so you can just copy and paste it in. It is just a one time thing so it shouldn't be too big of a deal.
You don't put parenthesis around localhost; it's just for (local) or (LocalDb)\v11.0. For localhost, it would be: DataSource=localhost for the default, unnamed local database (if one exists, which is not necessarily) or DataSource=localhost\SQLExpress for the default named installation of SQL-Server Express.
See http://www.connectionstrings.com/ for more info.
if you define your connection string section in the web.config as
<connectionStrings configSource="connections.config"/>
It will point to a separate config file, just containing the connection strings.
You can then add connection strings in code via the code below.
Note the advantage of this is that is does not have to reboot the website. Happy days...
using (StreamWriter writer = File.CreateText(#"c:\code\AVIVA_site\connections.config"))
{
writer.WriteLine("<connectionStrings>");
for (int i = 0; name.Length > i; i++)
{
writer.WriteLine("<add name=\"{0}\" connectionString=\"{1}\" providerName=\"{2}\" />", name[i], conString[i], provider[i]);
}
writer.WriteLine("</connectionStrings>");
writer.Close();
}
For the love of god...
if (!WebSecurity.Initialized)
{
WebSecurity.InitializeDatabaseConnection(
"DefaultConnection",
"Users",
"UserId",
"UserName",
true);
}
Instead of adding "DefaultConnection" I added the Configuration.ConnectionStrings["DefaultConnection"] instead.
The problem wasn't in the connection string in the web.config, but in the initializedatabase call...