且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

ProviderIncompatibleException在运行时第一次。但是,不是在第二次

更新时间:2023-02-25 20:40:36

  public partial class ProjectMgtContext:DbContext {
public静态字符串DefaultConnectionString;
public TestEntities()
:base(DefaultConnectionString)
{
}

然后更新DefaultConnectionString静态属性。如果您从模板生成上下文 - 编辑模板以添加如上所述的默认连接字符串。


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);
    ...
}

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.