问题
So, basically I'm using EF
with Reverse POCO Code First Generator
in my project.
My connection Strings look like this:
<connectionStrings>
<add name="HistoryDBContext" connectionString="" providerName="System.Data.SqlClient" />
<add name="ProjectMgtContext" connectionString="data source=xxx;initial catalog=xxx;user id=xx;password=xxx;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" />
</connectionStrings>
The idea is that I am going to read the connectionString
for HistoryDBContext
from ProjectMgtContext
(which is working fine) and then rewrite the connectionString
from HistoryDBContext
using:
public static void WriteConnectionString(string connectionString)
{
var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var connectionStringsSection = (ConnectionStringsSection) config.GetSection("connectionStrings");
connectionStringsSection.ConnectionStrings["HistoryDBContext"].ConnectionString = connectionString;
config.Save();
ConfigurationManager.RefreshSection("connectionStrings");
}
However, this only works the second time
that I run my project because during the first run, it complains that the connectionString
is empty:
So, obviously my approach is not working. How should I approach this?
Thank you
Edit
More code:
while (ProjectManager.HaveProjects())
{
var project = ProjectManager.GetNextProject();
if (project == null) continue;
/*Write the current project to the configuration file*/
Connection.WriteConnectionString(project.ConnectionString);
...
}
回答1:
Well most likely it won't work this way. EF might not re-read your connection string from configuration every time it needs it. It might as well cache either whole configuration or just connection string in memory. App.config is for connection strings that are not changing often during application runtime (or better at all). Just pass connection string to your ProjectMgtContext directly, or do like this:
public partial class ProjectMgtContext : DbContext {
public static string DefaultConnectionString;
public TestEntities()
: base(DefaultConnectionString)
{
}
And then update DefaultConnectionString static property. If you generate your context from template - edit template to add default connection string as above.
来源:https://stackoverflow.com/questions/32611063/providerincompatibleexception-when-running-first-time-but-not-in-second-time