ProviderIncompatibleException when running first time. But, not in second time

[亡魂溺海] 提交于 2019-12-25 02:59:45

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!