简体   繁体   English

实体框架(代码优先到现有数据库)-在运行时覆盖app.config中的连接字符串

[英]Entity Framework(Code First to an existing database) - overwrite a connection string in app.config at runtime

I need to connect my app(windows forms) to a SQL Server Database dynamically and i have in my app.config, 3 connection strings(where 1 of them i want to change dynamically). 我需要将我的应用程序(Windows窗体)动态连接到SQL Server数据库,并且在我的app.config中有3个连接字符串(其中1个我想动态更改)。

Bellow is the app.config: 波纹管是app.config:

  <connectionStrings>
    <add name="NfceConnPortalInterno"
         providerName="System.Data.SqlClient"
         connectionString="Data Source=lab;Initial Catalog=portal;Persist Security Info=True;User ID=micportal;Password=150302;language=us_english"/>

    <add name="NfceConnPortalExterno"
             providerName="System.Data.SqlClient"
             connectionString="Data Source=10.10.0.1,8081;Initial Catalog=portal;Persist Security Info=True;User ID=micportal;Password=\\-W?98xpT;language=us_english"/>


    <!-- this one will be modified in runtime. -->
    <add
      name="NfceContext"
      connectionString="data source=(localdb)\v11.0;initial catalog=Blogging;Connection Timeout=320;Persist Security Info=True;integrated security=True;language=us_english;MultipleActiveResultSets=True;App=EntityFramework"
      providerName="System.Data.SqlClient" />    

  </connectionStrings>

In my DbContext i have this: 在我的DbContext中,我有这个:

public NfceContext() : base("name=NfceContext")
{

}

Im trying an approach of changing this connectionString in a class, using AppDomain.CurrentDomain.SetupInformation.ConfigurationFile . 我正在尝试使用AppDomain.CurrentDomain.SetupInformation.ConfigurationFile在类中更改此connectionString的方法。 If i check running on debug mode, the connectionStrings on the app.vshost.exe.config is changed, but the app.config not(I guess that the app.config should be modified). 如果我检查在调试模式下运行,则app.vshost.exe.config上的connectionStrings会更改,但app.config不会(我想应该修改app.config)。

When i try to do for an example: context.MyEntity.ToList(), it´s gives me an error like this"you don´t have permission to create table..." and if i check the connection string at this time, it´s the old one(before i modify). 当我尝试举一个例子:context.MyEntity.ToList()时,它给我这样的错误,例如“您无权创建表...”,并且如果我此时检查连接字符串,它是旧的(在我修改之前)。

The code bellow can show what i said: 下面的代码可以显示我所说的内容:

Method to overwrite the connection string in the app.config: 覆盖app.config中的连接字符串的方法:

private void ModifyNfceContext(string dataSource, string portal, string senha)
{    
    XmlDocument xml = new XmlDocument();
    xml.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);

    XmlNodeList lista = xml.DocumentElement.SelectNodes(String.Format("connectionStrings/add [@name='{0}']", "NfceContext")); 
    XmlNode node = lista[0];

    string connectionString = node.Attributes["connectionString"].Value;
    SqlConnectionStringBuilder connStringBuilder = new SqlConnectionStringBuilder(connectionString);
    connStringBuilder.InitialCatalog = portal;
    connStringBuilder.DataSource = dataSource;
    connStringBuilder.IntegratedSecurity = true;
    connStringBuilder.UserID = "mic" + portal;
    connStringBuilder.Password = senha;

    node.Attributes["connectionString"].Value = connStringBuilder.ConnectionString;
    xml.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);    
}

The controller´s contructor: 控制器的构造器:

public NfceController()
        {
            if (this.context == null)
            {
                ModifyNfceContext(this.dataSource, this.portal, this.senha);
                //At this moment, the connectionString should be modified.
                this.context = new NfceContext();       
            }   

            this.repositoryNfce = new RepositoryNfce(context);
        }

So, what am i doing wrong? 那么,我在做什么错呢? Do i need to change the app.config instead of vhost.config? 我需要更改app.config而不是vhost.config吗?

I had written this article on setting connection strings at runtime for database first. 我写过这篇文章 ,首先介绍了在运行时为数据库设置连接字符串。 Check it out; 看看这个; it might be useful even in your case. 即使您的情况也可能很有用。

In short, you can create a partial class to get access to a DbContext constructor overload that takes a connection string as a parameter (example from my article): 简而言之,您可以创建一个子类来访问DbContext构造函数重载,该重载将连接字符串作为参数(来自我的文章的示例):

public partial class peopleEntities : DbContext
{
    public peopleEntities(String connectionString)
        : base(connectionString)
    {

    }
}

And then you can use EntityConnectionStringBuilder to build and pass the connection string (example also from my article): 然后,您可以使用EntityConnectionStringBuilder生成并传递连接字符串(示例也来自我的文章):

            EntityConnectionStringBuilder csb = new EntityConnectionStringBuilder();
            csb.Metadata = "res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl";
            csb.Provider = "System.Data.SqlServerCe.4.0";
            csb.ProviderConnectionString = "data source=people.sdf";
            String entityConnStr = csb.ToString();

If your NfceContext is not static object, you can create another constructor what will take a connection string name as the parametr, something like this: 如果您的NfceContext不是静态对象,则可以创建另一个构造函数,该构造函数将连接字符串名称作为参数,如下所示:

public class NfceContext : DbContext{
   public NfceContext (string appConfigConStrName) : base (appConfigConStrName) { }
}

Otherwise, if your context is static object, what is bad practice as I think, you can write public method what will create new instance of DbContext inside your NfceContext: 否则,如果您的上下文是静态对象,那么我认为这是一种不好的做法,您可以编写公共方法在NfceContext内创建DbContext的新实例的方法:

public class NfceContext : DbContext{
  static NfceContext context;

  public static NfceContext() {
     context = new NfceContext();
  }

  public void ChangeDB(string appConfigConStr) {
      context = new NfceContext(appConfigConStr);
  }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 App.Config中的实体框架连接字符串 - Entity Framework Connection String in App.Config 实体框架未在app.config中使用连接字符串 - Entity Framework not using connection string in app.config 在Entity Framework的app.config中更改连接字符串 - Changing connection string in app.config for Entity Framework 在app.config中找不到实体框架连接字符串 - Can't Find Entity Framework Connection String in app.config 实体框架代码首先没有app.config - Entity Framework Code First without app.config app.config和用于远程连接的实体框架 - app.config and Entity Framework for remote connection 覆盖C#Winforms中存储在app.config中的连接字符串 - Overwrite connection string stored in app.config in C# winforms 实体框架代码的动态连接字符串优先在运行时EF6(mssql,mysql,oracle)用于多个数据库提供程序 - Dynamic connection string for entity framework code first for multiple database providers at runtime EF6 ( mssql, mysql, oracle ) 不带App.config的实体框架,数据库优先,存储库模式,N层解决方案体系结构 - Entity Framework without App.config, Database first, Repository Pattern, N-tier Solution Architecture 强制实体框架和ASP.MVC使用另一个程序集的app.config中的连接字符串 - Forcing Entity Framework and ASP.MVC to use the connection string from app.config of another assembly
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM