【问题标题】:How to update Entity Framework Connection String如何更新实体框架连接字符串
【发布时间】:2014-03-02 01:48:14
【问题描述】:

我已经修改了 web.config 连接字符串。但是,在调试过程中,我仍然看到旧的连接字符串。

所以,我已经注释掉(并删除了)旧的连接字符串,但是通过服务器资源管理器添加了一个新的连接资源。 测试通过服务器资源管理器左侧面板上的向导连接 - 它显示已连接。

遵循此向导后,当我访问 web.config 时,我没有看到新的连接字符串。

问题:我怀疑,我没有按照步骤添加连接字符串 - 如何从设计器添加或更新连接字符串在设计器属性面板中,编辑显示为灰色,输出类型为构建到程序集,并且右键单击仅提供添加选项实体等,删除字符串并运行应用程序,不提示连接字符串向导

下面是字符串 -

<connectionStrings><add name="MaintRecordsDB_v1" connectionString="metadata=res://*/Models.DB.Model.csdl|res://*/Models.DB.Model.ssdl|res://*/Models.DB.Model.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=xxx.sample.net;initial catalog=MainDB;user id=maintRoot;password=hidden;multipleactiveresultsets=True;application name=EntityFramework&quot;" providerName="System.Data.EntityClient" /><add name="MainDBentities" connectionString="metadata=res://*/Models.DB.Model.csdl|res://*/Models.DB.Model.ssdl|res://*/Models.DB.Model.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=windflower.arvixe.com;initial catalog=MX_Dashboard;user id=maintRoot;password=hidden;multipleactiveresultsets=True;application name=EntityFramework&quot;" providerName="System.Data.EntityClient" /></connectionStrings>

编辑问题 2: 如何添加另一个 EF 连接字符串,例如MaintDB2 使用设计器,我在哪里手动更新。

【问题讨论】:

    标签: asp.net-mvc entity-framework web-config connection-string edmx


    【解决方案1】:

    在不知道你的上下文类是什么样子的情况下,比如说你的DbContext 类,如果它是生成的并假设它是部分的,你可以尝试使用一个构造函数向它添加另一个部分类部分,该构造函数将命名连接字符串作为论据。

    首先将命名连接添加到您的 app.config/web.config:

    <connectionStrings>
    ...
    <add name="MyOtherConnection" connectionString="metadata=res://*/blahblahblah;provider=System.Data.SqlClient;provider connection string=&quot;Data Source=ABunchOfOtherStuff;"
      providerName="System.Data.EntityClient" />
    </connectionStrings>
    

    然后在另一个(非生成的)文件中添加一个匹配的部分类,并使用构造函数来获取连接字符串名称:

    // the class name must match the name of your existing context
    public partial class MyContext : DbContext
    {
        public MyContext(string connectionStringName) : base("name=" + connectionStringName)
        {
        }
    }
    

    然后通过传入连接字符串的名称来使用您的上下文,由一些无用的代码演示:

    // ...
    using (var context = new MyContext("MyOtherConnection"))
    {
       var id = 1;
       var collection = context.MyEntities.Where(a => a.ID == id).ToList();
    }
    

    【讨论】:

      【解决方案2】:

      在 MVC 中,有几件事是基于 Convention。它更喜欢约定而不是配置。按照惯例,这两件事之间应该有联系。 DbContext 的类名与连接字符串匹配,以使其按约定

      正常工作
      1. 继承自 DbContext 的类说

        公共类 DbPersonContext : DbContext { ... }

      2. 必须有一个名为Person

      3. 的连接字符串

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-11-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-10-11
        • 2014-02-03
        • 2011-04-16
        相关资源
        最近更新 更多