【问题标题】:Connection to SQL server with EnitityFramework 6 code first首先使用 EnitityFramework 6 代码连接到 SQL 服务器
【发布时间】:2016-12-01 14:50:16
【问题描述】:

好的,我的项目有一个单独的类库,其中包含所有 EnitityFramework 6.1.3 版代码和设置。

除了我的本地 sql db 之外,我无法让它连接到任何东西

我可以使用 SQL 管理器、SQL 服务器对象资源管理器和 LINQpad 连接到我的 sql 框 192.111.111.111\sql_box。所以它在那里并且连接字符串是正确的。

我想我现在打算做基于代码的配置

所以我的 App.cong 看起来像这样

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>

  <entityFramework>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>

  <entityFramework codeConfigurationType="MyProject.CodeConfig, MyProject">
  </entityFramework>

</configuration>

我还创建了派生自 DbConfiguation 的类

  public class CodeConfig : DbConfiguration
    {
        public CodeConfig()
        {
            this.SetProviderServices("System.Data.SqlClient",
                System.Data.Entity.SqlServer.SqlProviderServices.Instance);
        }
    }

但是我把 192.111.111.111\sql_box 放在哪里

每次我在包管理器中运行 Update-Database 时都会得到

在建立与 SQL Server 的连接时发生与网络相关或特定于实例的错误。服务器未找到或无法访问。验证实例名称是否正确以及 SQL Server 是否配置为允许远程连接。 (提供者:SQL 网络接口,错误:26 - 错误定位服务器/指定的实例)

【问题讨论】:

    标签: sql-server entity-framework ef-code-first entity-framework-6


    【解决方案1】:

    在 web.config 或 app.config 中。

    <configuration>
        <connectionStrings>
           <add name="YOURDBCONTEXTNAME" connectionString="data source=SERVER;initial catalog=DATABASE;Integrated Security=false;persist security info=True;user id=USER;password=PASSWORD;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" />
    

    【讨论】:

      【解决方案2】:

      您的连接字符串需要位于 启动项目 的 web/app 配置文件中。

      类库中的连接字符串(假设不是启动项目)在进行模型更改、迁移等时使用。

      【讨论】:

      • 我必须在这里变得愚蠢,对此感到抱歉。但是我已将 connectionStrings 放在作为启动的 MVC 项目的 Web.Config 中。 MVC 项目中没有 EntityFramework,因此当我将包管理器指向 MVC 项目并输入 Update_database 时,我被告知“项目中未安装 EntityFramework 包”,当我安装它时,似乎希望所有迁移内容都是在MVC项目中
      猜你喜欢
      • 1970-01-01
      • 2012-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-06
      • 1970-01-01
      • 2015-02-17
      • 2011-08-02
      相关资源
      最近更新 更多