【问题标题】:EF Code First with SQL Server Express 2012 ConnectionStringEF Code First 与 SQL Server Express 2012 ConnectionString
【发布时间】:2012-04-26 18:21:03
【问题描述】:

使用以下连接字符串一切正常。

<add name="ApplicationServices" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true" providerName="System.Data.SqlClient" />

我最近在本地计算机上安装了 SQL Server 2012 Express 进行测试,但无法建立连接。这是我使用 Windows 身份验证的连接字符串。

<add name="ApplicationServices" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=testdb;Integrated Security=SSPI;" providerName="System.Data.SqlClient" />

我是一个尽最大努力搜索论坛的菜鸟,但我无法从“具有相似标题的问题”部分推迟我的解决方案。非常感谢任何帮助。

【问题讨论】:

    标签: ef-code-first sql-server-2012-express


    【解决方案1】:

    EntityFramework 代码首先在 app.config 或 web.config 文件中使用 defaultConnectionFactory,它将自动连接到 .\SQLEXPRESS。此配置如下所示:

    <entityFramework>
        <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework"/>
      </entityFramework>
    

    如果您使用的是 EF Code First,您可能有一个派生自 DbContext 的类用作上下文。按照设计,EntityFramework 将查找与您的上下文类同名的连接字符串,并使用该连接字符串而不是 defaultConnectionFactory。这就是我使用它的方式:

    <connectionStrings>
        <add name="ObjectContext" 
             connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=My.Db.Name; Integrated Security=True; MultipleActiveResultSets=True"
             providerName="System.Data.SqlClient"/>
      </connectionStrings>
    

    我的建议是检查 EF 是否使用它的 defaultConnectionFactory,甚至通过添加以您的上下文命名的连接字符串来强制覆盖它。 您还应该查看this blog article,它提供了有关 EF 配置文件的详细信息。

    【讨论】:

    • 我很抱歉花了这么长时间将其标记为我的解决方案。我在另一个爱好(如果您已婚,则为丈夫)项目上受到关注,现在又回到了这个。我的连接字符串被覆盖,发布后我没能抓住它。
    【解决方案2】:

    您确定这部分连接是正确的吗? "数据源=.\SQLEXPRESS [名称];

    我没有使用 SQL Server 2012,但尝试删除 [Name] 文本。

    【讨论】:

    • 我很抱歉。连接字符串如下。 connectionString="数据源=.\SQLEXPRESS;目录=myHub;集成安全=SSPI;" providerName="System.Data.SqlClient"
    • 我也试过 connectionString="Data Source=.\SQLEXPRESS;Integrated Security=SSPI;" providerName="System.Data.SqlClient"
    【解决方案3】:

    这对我有用

    add name="MovieDBContext" connectionString="Data Source=.\SQLEXPRESS;
    Initial Catalog=Movies;
    Integrated Security="True" providerName="System.Data.SqlClient"
    

    我正在学习本教程并且必须完成它。 MovieDBContext 是在 mvc 应用程序模型中的代码中创建的

    public class MovieDBContext : DbContext
    {
        public DbSet<Movie> Movies { get; set; }
    }
    

    这会自动创建控制器类的 IDE,但在我在 web.config 文件中正确获取连接字符串之前它不会工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-08
      相关资源
      最近更新 更多