Reputation: 26511
I've noticed that when I create model-first database using EF it is ignoring web.config connection strings and doing it's own thing in the background. Then I found a way to set my own connection string in constructor like so.
public class MainDataContext : DbContext
{
public MainDataContext()
{
this.Database.Connection.ConnectionString = "MY CONNECTION STRING THAT IS ACTUALLY USED";
}
}
Question: How can I force/set it to use connection string from web.config?
I've been told that if you name your connection string just like your data context it will work but it doesen't for me. I know for sure that it does not work if I name it DefaultConnectionString
.
<add name="MainDataContext" providerName="System.Data.SqlClient"
connectionString="Server=(LocalDB)\\v11.0;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|ProjectDB.mdf;" />
Error occurred when I try to do update-database -v -f
from console.
Upvotes: 2
Views: 1799
Reputation: 7058
You can try something like this:
public MainDataContext() :
base(typeof(MainDataContext).Name)
{
}
Are you sure your connection string declaration in the Web.config is correct? Like this:
<?xml version="1.0"?>
<configuration>
<connectionStrings>
<add name="MyDatabase" connectionString="server=localhost;User Id=user;password=password;Persist Security Info=True;database=mydatabase" providerName="MySql.Data.MySqlClient" />
</connectionStrings>
</configuration>
Upvotes: 1