【问题标题】:Connection to the database failed. Check that connection string is correct and DbContext constructor与数据库的连接失败。检查连接字符串是否正确以及 DbContext 构造函数
【发布时间】:2014-03-26 02:45:56
【问题描述】:

访问数据库时出错。这通常意味着与数据库的连接失败。检查连接字符串是否正确,以及是否使用了适当的 DbContext 构造函数来指定它或在应用程序的配置文件中找到它。

我发誓我什么都试过了!阅读本教程并努力获得与数据库的连接。

我在 SQL Server 2012 中的表名为“tblEmployee”,数据库名为“Sample”

这是 Employee.cs 类

[Table("tblEmployee")]
public class Employee
{
    public int EmployeeID { get; set; }
    public string Name { get; set; }
    public string City { get; set; }
    public string Gender { get; set; }
}

这是员工上下文模型类

public class EmployeeContext : DbContext
{
    public DbSet<Employee> Employees { get; set; }
}

这是 EmployeeControler

public class EmployeeController : Controller
{
    public ActionResult Details()
    {
        EmployeeContext employeeContext = new EmployeeContext();
        Employee employee = employeeContext.Employees.Single(emp => emp.EmployeeID == 2);
        return View(employee);
    }
}

这是 web.config 文件

<entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
    <parameters>
        <parameter value="v11.0" />
    </parameters>
   </defaultConnectionFactory>
    <providers>
    <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
</entityFramework>

这是连接字符串

<connectionStrings>
    <add name="EmployeeContext" connectionString="Data Source=ADMIN-PC;Initial Catalog=Sample;Integrated Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False" providerName="System.Data.SqlClient" />
</connectionStrings>

实际视图没有什么特别的

@{
ViewBag.Title = "Employee Details";
}

<h2>Employee Details</h2>

<table style="font-family:Arial">
    <tr>
        <td>EmployeeID:</td>
        <td>@Model.EmployeeID</td>
    </tr>
    <tr>
        <td>Name:</td>
        <td>@Model.Name</td>
    </tr>
    <tr>
        <td>Gender:</td>
        <td>@Model.Gender</td>
    </tr>
    <tr>
        <td>City:</td>
        <td>@Model.City</td>
    </tr>
</table>

这是堆栈跟踪

at System.Data.Entity.ModelConfiguration.Utilities.DbProviderServicesExtensions.GetProviderManifestTokenChecked(DbProviderServices providerServices, DbConnection connection)
at System.Data.Entity.DbModelBuilder.Build(DbConnection providerConnection)
at System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext internalContext)
at System.Data.Entity.Internal.RetryLazy`2.GetValue(TInput input)
at System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
at System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()
at System.Data.Entity.Internal.Linq.InternalSet`1.get_InternalContext()
at System.Data.Entity.Infrastructure.DbQuery`1.System.Linq.IQueryable.get_Provider()
at System.Linq.Queryable.Single[TSource](IQueryable`1 source, Expression`1 predicate)
at MVCDemo.Controllers.EmployeeController.Details() in c:\Users\Admin\Documents\Visual Studio 2013\Projects\MVCDemo\MVCDemo\Controllers\EmployeeController.cs:line 19
at lambda_method(Closure , ControllerBase , Object[] )
at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass37.<>c__DisplayClass39.<BeginInvokeActionMethodWithFilters>b__33()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass4f<InvokeActionMethodFilterAsynchronously>b__49()

【问题讨论】:

  • 那么你的SQL Server叫ADMIN-PC,window用户(应用程序池)有权限吗?使用 SQL Sever Management Studio 验证您是否可以连接到数据库。
  • 查看 InnerException,“提供程序没有返回 ProviderManifestToken 字符串。”啊!
  • 是的@ElectricLlama,我打开了 Management Studio,我可以连接到数据库。这就是我最初用来制作数据库的方法。我什至通过在我的桌面上创建一个 Test.udl 文件并测试连接来测试连接,它工作正常! .udl 文件上的服务器名称列为“ADMIN-PC”。我认为这与我拥有的 EF 代码有关
  • 接下来,您使用的是Integrated Security=True,这意味着使用windows帐户进行连接。通过 SSMS 和 UDL,这就是你。通过您的应用程序,这可能是应用程序池标识。您可以尝试使用 SQL Profiler 来比较成功和失败的登录尝试,它会告诉您哪个 Windows 用户正在尝试登录(如果有)。您也可以暂时尝试使用 SQL 用户来验证这是否是问题所在。
  • 这是我在检查 Manifest 错误时发现的:stackoverflow.com/questions/4741499/…

标签: c# sql-server asp.net-mvc entity-framework


【解决方案1】:

原因:当您使用 IIS 时,您的应用程序池用户可能是“ApplicationPoolIdentity”。连接到网络资源时,它将作为本地系统连接(因此,如果在域中,那将是 domain\computer$ 帐户)。大概该帐户无权访问 SQL DB。

某种修复:您对 IIS Express 的更改“修复”了这个问题,连接是作为当前用户建立的。不过,如果您打算部署到 IIS,那就不好了。

更好的解决方法:将您的 IIS 应用程序池用户更改为真正的 Windows 用户帐户,该帐户可以访问 SQL DB。

我刚刚遇到了完全相同的问题,并且可以确认上述修复对我有用。

【讨论】:

  • 我可以确认这是成功的。比我的解决方案好得多,所以我把这个作为答案:) 干杯!
【解决方案2】:

包含 web.config 文件(包含连接字符串)的主项目未设置为默认项目。将其设置为默认项目即可解决问题。

【讨论】:

    【解决方案3】:

    我有类似的错误并已修复。当我在解决方案中设置包含我的 ApplicationDbContext 类的“启动项目”时,我有两个以上的模块。右键模块>>点击“设置为启动项目”

    【讨论】:

      【解决方案4】:

      在与这整件事进行了相当多的斗争之后,这对我有用:

      -1) 已卸载 SQL Server

      -2) 重新安装 SQL Server 并设置一个新的实例(INST01)

      ^^我认为以上任何一个实际上都没有做任何事情。

      -3) 通过转到 SQL Server 对象资源管理器并找到新实例,使用 Visual Studio 重新连接到新服务器。

      -4) 回到 SQL Server Management Studio 并重新创建了我的简单数据库。

      -5) 在 SQL Server 对象资源管理器下,我从数据库属性中复制了连接字符串。

      -6) 我将项目的 Web 属性从本地 IIS 更改为 IIS Express。

      -7) 已卸载 EntityFramework 6

      -8) 删除了 web.config 文件中对实体框架的任何引用(这样在安装时将插入 EF 5 的代码)

      -9) 从包管理器控制台安装 EntityFramework 5.0.0。

      -10) 运行应用程序,它工作正常。

      我不是 100% 确定问题出在哪里,但我认为这与本地 IIS 和 IIS Express 有关。我认为有必要更改 EF 框架版本以确保调用表的语法一致。

      请记住,在所有这些之前,我可以通过简单地进入 SQL Server 对象资源管理器来建立与数据库的连接。我什至可以在 Visual Studio 中调出表格并查看数据。

      希望这可以帮助某人:)

      【讨论】:

      • 很高兴您对它进行了排序。如果可以的话,你应该接受你的答案。
      • 也许你可以尝试卸载 EF5 并重新安装 EF6 以检查是否可以重现问题?如果是,那么你非常接近原因,无论如何,恭喜你解决了你的问题:-)
      • 是的,我有同样的错误消息,当我最初从 IIS Express 更改为 IIS 时显示。必须是未配置身份/权限的问题。如果我找到它会发布答案。
      • 由于兼容性问题,我最终只是删除了 entityframework 6 并将其重新安装到最新版本而不是版本 5,并且工作正常,没有更改任何其他内容。
      【解决方案5】:

      如果你的服务器是 2012 sql express 免费版,那么你的连接字符串应该是这样的。

      <connectionStrings>
      <add name="EmployeeContext" connectionString="Data Source=ADMIN-PC\SQLEXPRESS;Initial       Catalog=Sample;Integrated Security=True;Connect  timeout=15;Encrypt=False;TrustServerCertificate=False"
      providerName="System.Data.SqlClient" />
      

      数据源应该是=Admin-PC\SQLEXPRESS...

      也看看这个SQL 2012 Connection Strings

      【讨论】:

      • 我通过拉起“SQL Server 对象资源管理器”复制了连接字符串,然后找到数据库并转到属性。
      • 但是你是sql server express还是其他版本?
      • 我使用的是 SQL 标准版
      【解决方案6】:

      更新

      参考DbConfiguration Class

      从这个类派生的类可以放在同一个程序集中 从 DbContext 派生的类来定义实体框架 应用程序的配置。通过调用设置配置 受保护的方法和设置此类的受保护属性 派生类型的构造函数。使用的类型也可以是 在应用程序的配置文件中注册。

      DbConfiguration 派生类应与 DbContext 位于同一程序集中。

      以我的 ADO.NET 实体数据模型为例,我发现我的类派生自 Model1.edmx -> Model1.Context.cs -> Model1.Context.cs 的 DbContext。

      代码假设配置您的清单令牌并希望它解决您的问题。


      我找到了类似的问题讨论here,希望可以帮助您解决问题。

      参考moozzyk,

      好消息是,要解决该问题,您实际上不必更改 EF 代码。

      EF6 允许配置服务,其中一项服务允许覆盖获取提供者清单令牌的默认行为。

      您可以使用基于代码的配置注册您的自定义 ma​​nifest token resolver 并返回硬编码值(例如,如果您始终针对 SqlServer 2012 运行,则只需返回“2012”)或提出你自己的版本。

      这应该会阻止 EF 检查您的应用运行的数据库版本

      如果您针对不同版本的 Sql Server 运行,您可以使用 DbConnection.ServerVersion 属性为您的数据库创建一个provider manifest token

      这是一个示例 - 您只需复制/粘贴即可,它应该可以工作,因为 EF 应该检测 配置 *自动*(只要 DbConfiguration 派生类是在与您的上下文相同的程序集中)

      public class Configuration : DbConfiguration
      {
          public Configuration()
          {
              SetManifestTokenResolver(new ManifestTokenResolver());
          }
      }
      
      public class ManifestTokenResolver : IManifestTokenResolver
      {
          public string ResolveManifestToken(DbConnection connection)
          {
              // The simplest thing is just to return hardcoded value
              // return "2012";
      
              try
              {
                  connection.Open();
      
                  var majorVersion =
                      Int32.Parse(connection.ServerVersion.Substring(0, 2), CultureInfo.InvariantCulture);
      
                  if (majorVersion == 9)
                  {
                      return "2005";
                  }
      
                  if (majorVersion == 10)
                  {
                     return "2008";
                  }
      
                  return "2012";
      
              }
              finally 
              {
                  if (connection.State == ConnectionState.Open)
                  {
                      connection.Close();
                  }
              }
          }
      }
      

      【讨论】:

      • 我不确定我把这段代码放在哪里。在 EmployeeContext.cs 中?似乎它需要自己的课程。我迷路了>_>
      • 在我的 ADO.NET 实体数据模型的情况下,我发现我的类派生自 DbContext 在 Model1.edmx -> Model1.Context.cs -> Model1.Context.cs。可能你可以尝试搜索关键字DbContext
      • 明天早上我会试一试。我也将尝试重新安装 SQL Server
      • 我试过这个但没有成功:(,至少我学到了一些东西!
      • 我对您的评论进行了一次更新,因为您试图提供帮助,但不确定是谁投了反对票。
      【解决方案7】:

      在 IIS 上托管我的 MVC 应用程序时,我也面临同样的问题。 错误:无法打开登录请求的数据库“MVCDemo”。登录失败。用户“IIS APPPOOL\ASP.NET v4.0”登录失败。

      临时修复本地用户不用于部署:我们可以通过 IISExpress 使用,而不是部署在 IIS 上,转到项目-->属性-->Web-->启用单选按钮,使用本地 IIS 服务器并勾选使用 IIS Express 设置。

      系统规格:VS 2012,

      【讨论】:

        猜你喜欢
        • 2018-05-20
        • 2018-04-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-03
        • 2020-05-20
        • 2019-12-11
        相关资源
        最近更新 更多